75 Commits
Author SHA1 Message Date
nessarandClaude Opus 5.5 b50f429f2a Document the relay as deployed: Komodo, NPM behind Cloudflare, public (#151)
CI / relay (pull_request) Successful in 27s
CI / core (pull_request) Successful in 1m40s
CI / relay (push) Successful in 40s
CI / core (push) Successful in 57s
The stack passes its variables through environment: (Komodo's .env only
fills the placeholders), the key is a Komodo Secret, and the personal key's
limits apply until #152. NPM takes the player's address from
CF-Connecting-IP and keeps no access log. Cloudflare must not challenge or
cache the subdomain. The service is public by choice, with the location
block that would restrict it. Updates and key changes go through Redeploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:48:43 +01:00
nessarandClaude Opus 5.5 90aeda60dd Publish Riot's new verification code (#147)
CI / relay (push) Successful in 28s
CI / core (push) Successful in 1m45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:44:19 +01:00
nessarandClaude Opus 5.5 86b149135c Count the Riot request's description as sent (#147)
CI / relay (pull_request) Successful in 53s
CI / core (pull_request) Successful in 1m12s
CI / relay (push) Successful in 27s
CI / core (push) Successful in 1m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:39:46 +01:00
nessarandClaude Opus 5.5 be0ddfabfe Publish Riot's verification code at /riot.txt (#147)
CI / relay (pull_request) Successful in 52s
CI / core (pull_request) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:39:39 +01:00
nessar 324a092c47 Update docs/demande-cle-production.md
CI / relay (pull_request) Successful in 25s
CI / core (pull_request) Successful in 1m47s
2026-11-27 18:38:19 +01:00
nessarandClaude Opus 5.5 c9cb0f4ed7 Fit the Riot request's description in the form's 1,500 characters (#147)
CI / relay (pull_request) Successful in 31s
CI / core (pull_request) Successful in 1m50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:36:28 +01:00
nessarandClaude Opus 5.5 1a9dea471d Name the real subdomain, arena-tracker.nessar.fr, in the Riot request (#147)
CI / relay (pull_request) Successful in 40s
CI / core (pull_request) Successful in 57s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:34:17 +01:00
nessarandClaude Opus 5.5 e7103ae0bd Record the production key request as Riot's form takes it (#147)
CI / relay (pull_request) Successful in 34s
CI / core (pull_request) Successful in 1m40s
The description is one plain-text field: the text is now the exact block
pasted, with the other fields in a table, and what must stay true of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:34:01 +01:00
nessarandClaude Opus 5.5 003ba4872c License under the AGPL 3.0 or later, and draft the production key request (#147)
CI / relay (pull_request) Successful in 42s
CI / core (pull_request) Successful in 1m0s
LICENSE holds the FSF's AGPL 3.0 text; the three crates declare
AGPL-3.0-or-later. The README says what stays under its own license: the
Inter and Unbounded fonts (OFL) and Riot Games' images, data and
certificate. Every dependency's license is compatible.

docs/demande-cle-production.md is the text for Riot's developer portal:
the app, the six Riot calls and when each is made, the relay and its
limits, the friend lookup by Riot ID, no item or augment statistics, and
that today's app still uses each player's personal key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:32:11 +01:00
nessarandClaude Opus 5.5 24691306fb Fill the site's placeholders, name Cloudflare, add screenshots (#145)
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m1s
CI / relay (push) Successful in 43s
CI / core (push) Successful in 1m3s
Operator Nessar, contact arena@nessar.fr, effective 27 November 2026,
14 days for gitea.nessar.fr access logs. The privacy policy now says
requests pass through Cloudflare, which sees them in transit.

Three screenshots of the app on the home page (Challenge, Matches,
Statistics), WebP at 1280 px, other players' Riot IDs blurred. The relay
serves them like the pages; its test now walks all of site/, so a file
left out of src/site.rs fails CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:24:48 +01:00
nessarandClaude Opus 5.5 c7d0395502 Package the relay as a container image, published by a local script (#151)
CI / relay (pull_request) Successful in 36s
CI / core (pull_request) Successful in 52s
CI / relay (push) Successful in 27s
CI / core (push) Successful in 2m5s
A static musl binary on an empty image, run as nobody, listening on 8080.
scripts/publish-relay builds it from a clean, pushed commit of develop or
main and pushes it to Gitea's registry, tagged with the commit and latest.
The build context is an allowlist: never .env nor target/.

RELAY_TRUSTED_PROXY also takes a network: Nginx Proxy Manager's address on
the Docker network changes when it restarts.

docs/service-relais.md gives the compose service, the env file, the NPM
proxy host (no access log, Access List until #152), and how to update,
change the key and check the restart and the per-address limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:42:56 +01:00
nessarandClaude Opus 5.5 fe36a431dc Relay the app's Riot calls with the key and the quota, and serve the site (#148, #145)
CI / relay (pull_request) Successful in 37s
CI / core (pull_request) Successful in 52s
CI / relay (push) Successful in 40s
CI / core (push) Successful in 1m6s
New workspace member arena-tracker-relay: it holds the Riot key from the
environment and serves the app's six Riot calls as /{routing value}{Riot path}.
Any other route, method, routing value, queue or count above 100 gets 404
without calling Riot. Fixed-window limits per routing value (production
limits) and per client address answer 429 with Retry-After at once; a Riot
429 is passed with its delay and suspends its routing value. Riot's 401/403
become 503 (except a timeline's 403), an unreachable Riot 502. The log holds
the call type, status and duration only; nothing is written to disk.

The same binary serves the site pages of site/ (#145), built in, unlogged.

Tested over HTTP against a local fake Riot. A separate `relay` CI job, now
required on develop and main. ADR-0008 replaces ADR-0001's personal key;
docs/service-relais.md says how to run it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:20:34 +01:00
nessarandClaude Sonnet 5.5 a694cbd8e7 Draft the Arena Tracker website pages (#145)
Home page, Terms of Service and Privacy Policy for the production key
application (#144). Bracketed fields and screenshots are still to be filled in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:20:34 +01:00
nessarandClaude Opus 5.5 67caf7861c Wait for the log writer in its tests instead of Log::flush's 2 s (#142)
CI / core (pull_request) Successful in 1m48s
CI / core (push) Successful in 49s
On the slower CI runner, flush gave up while the writer was still
rotating 3.5 MB, and the test saw only the old file. The tests now send
the writer the same flush message and wait for its answer without limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:58:03 +01:00
nessarandClaude Opus 5.5 3d4c8bbc83 Address review: Journal private, client found/gone, sync redaction test (#142)
CI / core (pull_request) Failing after 1m45s
- Rule #3: Journal and its open/launch are private again; the writer's
  tests move to src/journal/tests.rs, only the launch test stays an
  integration test. The « Ouvrir le dossier des journaux » selector sits
  on the button itself, not on a div drawn for the test.
- The log notes the League client found and gone (its event stream
  connects or drops), and a client without anyone signed in reads
  "nobody signed in" instead of "absent".
- Other libraries (GPUI…) reach the log only with errors: their info and
  warnings may come per frame. The HTTP client stays out entirely.
- The log opens after the single-instance check: a relayed launch no
  longer writes to, nor rotates, the running instance's log.
- A whole sync through the Riot adapter is tested to log neither the key
  nor a full PUUID. The URL comment follows the spec: Riot IDs may be
  logged, a full PUUID may not.
- --verify-release keeps its eprintln: the publishing script reads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:52:48 +01:00
nessarandClaude Opus 5.5 cb6fbcadaf Follow Rule #3: no wrapper drawn only for a test (#143, #142)
CI / core (pull_request) Successful in 1m56s
Each alert sat in a div that only gave tests a selector; it is gone, and
the tile test keeps what #143 asks: the tiles never get taller with the
official count. The folder opener's comment states its production role.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:11 +01:00
nessar 556e95eadc Merge #142: keep an application log, open its folder from « Paramètres » 2026-11-27 16:22:11 +01:00
nessar 04b1204432 Merge #141: open « Statistiques » from a chart icon in the banner's corner 2026-11-27 16:22:11 +01:00
nessar c25dc99db4 Merge #138: a click anywhere in a text field gives it the keyboard 2026-11-27 16:22:11 +01:00
nessarandClaude Opus 5.5 4ac19df72b Address review: release version, rotation failure, low priority (#142)
The launch line carries the release version (`-dev` suffix on a dev build). A failed
rotation keeps writing to the current file and retries after another MB. The writer thread
runs an `on_start` hook, which the app uses to lower its priority. Tests for the rotation
failure and the `ureq`/debug exclusion. The profile CSV errors go to the log. Opening the
logs folder only clears its own error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 be2eee469e Address review: ring structural test, doc fixes, kit icon_assets! macro (#141)
Hovering the icon leaves the cached ring unrendered (asserted in the grid
test). performance.md opens « Statistiques » by the chart icon, and
interface.md no longer claims the icon leaves the text untouched in a
narrow window. The chart icon comes from gpui_kit::assets::icon_assets!, so
the vendored SVG and Lucide license are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessar ffe71de4da Merge #143: drop the official count note from the « Statistiques » tiles 2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 78cbc87e68 Address review: state that the field buttons also focus the field (#138)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 200a1f380c Keep an application log in a rotating file, and open its folder from « Paramètres » (#142)
Lines are queued to one writer thread, idle at rest, that flushes once the
queue is drained and on quit. Riot calls are logged by type, never by URL;
PUUIDs are cut to 8 characters and the key never appears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 771f6f3d31 Put « Statistiques » on a chart icon in the banner's bottom-right corner (#141)
The text link at the end of the Season line is gone. The one Lucide icon the
kit's default bundle lacks is served by the app's own asset source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessar 5be6093a40 Merge #146: show Riot's legal notice in « Paramètres » 2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 8fa4779e2d Address review: correct two comments on the official note tests (#143)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 aa5db4036e Give a text field the keyboard on a click in its padding or border (#138)
gpui-component's Input frame tracks its own focus handle, apart from the
editor's: a click off the text line focused the frame and typing went
nowhere. One app-side wrapper focuses the field's state instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 bb6ab65559 Address review: prove the Riot notice is reachable, fix the top being cut off, move docs (#146)
The test now scrolls the settings down and checks the notice ends inside the
window and the title starts inside it. Doing so showed the my_auto centring
pushed the overflowing column's top out of the scroll range; a min-height
wrapper centres it instead. The notice sentence moves to its own doc section
and mentions the first-launch key screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 45adf219d7 Drop the official count note from the « Statistiques » tiles (#143)
The tiles are now all built the same way; the mismatch alert stays the only
signal of an incomplete history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 dd8af3f9e7 Show Riot's legal notice at the bottom of « Paramètres » (#146)
The settings now scroll, so the notice stays reachable at the window's
minimum size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 c3003930f1 Ignore .scratch/, the local working drafts
CI / core (push) Successful in 1m51s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:59:04 +01:00
nessar 8b6062aebc Center player stats and scroll to the viewed account in a chosen Match
CI / core (pull_request) Successful in 1m54s
CI / core (push) Successful in 1m58s
2026-11-25 22:50:55 +01:00
nessar d2f5a6b96d Protect account deletion and address the account and match UI review (#139)
CI / core (pull_request) Successful in 1m44s
2026-11-25 22:39:53 +01:00
nessarandClaude Sonnet 5.5 0f13ecbc80 Add Friends by their Riot ID from the Account selector (#116)
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>
2026-11-25 20:08:27 +01:00
nessarandClaude Opus 5.5 d601d30605 Delete an Account or a Friend from « Paramètres » (#117)
- New « Comptes » section in the settings (settings/accounts.rs): your Accounts then your
  Friends, each with « Supprimer », an inline confirmation with the count of stored Matches and
  the client-only sentence, « Annuler », and a greyed button for the Account signed in to the
  client. The summary and the deletion run on a low-priority thread; the lists are read when
  « Paramètres » opens and after a deletion, the signed-in state when the section renders.
- KeyForm takes the tracker and emits KeyEvent::AccountDeleted; Page::account_deleted reads the
  Accounts again and shows the active Account when the deleted one was pinned.
- Tests, guide d'utilisation and interface spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:08:27 +01:00
nessarandClaude Sonnet 5.5 97cd91e9b9 Put the Défi's banner on « Parties » and play the end of a Match there (#110)
- « Parties » draws the Défi's banner (Season, counter, ring) on the splash of the Match
  chosen, whose tick is lit; none chosen, nothing shown nor lit. The dressing moves to
  home/dress.rs (banner.rs would pass 500 lines).
- The playback knows its screen: the end of a Match that opens its recap plays on « Parties »
  once the new Match is chosen, else on « Défi ». `challenge_visible` becomes
  `playback_visible`; the list read plays what waits.
- « Défi » shows the final state afterwards, without a second play.
- « Parties » lays the banner over a column that scrolls in a low window; tests that read a
  whole recap use a taller window.
- Interface spec and user guide updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:08:27 +01:00
nessarandClaude Opus 5.5 4392191a22 Add Friends by Riot ID and delete Accounts in the core (#116, #117)
- add_friend resolves a Riot ID, refuses it with a French reason (malformed,
  unknown, other region, no key) or answers the stored Account, and stores a
  Friend with the platform its region gives (accounts.friend, migrated)
- import_friend imports a Friend's history: the current Season first, then
  the rest, resumes from the listing when cut, then lists only since the mark
  sync also uses; Mastery Points once per call, on the stored platform when
  the Friend has no Match yet
- Each request of a Friend's import waits on a Condvar while a follower round
  or refresh runs or a finished game's Match is awaited
- account_summary and delete_account: Match count and client-only details for
  the confirmation; one transaction removes Matches, points, marks, blocks and
  the Death Recaps no other Account shares; the follower forgets the Account
  so it is adopted again with a full import
- RiotApi asks the active region by puuid and maps platforms to routing
  regions; marks and points are not written for a deleted Account

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:08:03 +01:00
nessarandClaude Sonnet 5.5 c9d53055d9 Light the ring's tick under the pointer and present its champion (#112)
- Hovering the crown aims at the nearest tick by angle (`ring/aim.rs`, a band a little wider
  than the ticks); the tick lights and the banner fades to that champion's splash.
- The banner's first line becomes the champion's (validé le … · N Tentatives / N Parties ·
  meilleur Placement / jamais joué); the second is hidden but keeps its height.
- The hover is a layer over `dress_banner`'s rest state (`page/ring_hover.rs`): leaving the crown
  clears it. Listeners sit on a non-cached slot around the ring; nothing happens until the aimed
  tick changes, and it is ignored while the end of a Match plays.
- Page tests for the aim, the three lines, rest on « Défi » and « En partie », no new render
  without a change of tick, the two-splash sweep and the no-fade setting; docs updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:08:03 +01:00
nessarandClaude Opus 5.5 cae84c1577 Show the active Account when the end of a Match shows Défi (#115)
- With « Ouvrir le récapitulatif en fin de Partie » off, or a game ended
  without its block, the end decides like a phase: an Account picked in the
  top bar gives way to the active one, whose Challenge shows.
- Rewrap the « Parties » module comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:07:48 +01:00
nessarandClaude Opus 5.5 644a47743d Choose the Account of Défi, Statistiques and Parties in the top bar (#115)
- The top-bar selector lists the active Account first and now also drives
  « Parties » (enabled there, grayed only during a phase); the "never the
  pinned Account" rule and history_account are gone.
- Choosing another Account resets both « Tous » filters and recomputes its
  statistics once on the background worker (show_account -> rescope).
- Entering or leaving a phase, and opening the recap of the active
  Account's Match, bring the active Account back; follow_match_end matches
  Matches against the active Account.
- The banner overline of another Account starts with « Défi de Pseudo · ».
- Tests in account_selector.rs, two old tests rewritten; interface spec and
  user guide updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:07:48 +01:00
nessarandClaude Opus 5.5 d21d4a90dd Show the last played champion on the Défi's banner (#111)
- The home banner's illustration is the splash of the champion of the Season's last Match
  (the « Dernière Partie » line's, all Formats), none without a Match, instead of the last
  champion validé's.
- The comet reveals the new splash when its Match is the last Match; a Match that arrived
  late just sets the banner's splash, as before.
- interface.md says it; tests cover the choice and the reveal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:04:32 +01:00
nessarandClaude Opus 5.5 33413e7bf4 Say why a single click on the notification icon does nothing (#113)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:04:32 +01:00
nessarandClaude Haiku 5.5 e81611371f Reopen the window on a double-click of the tray icon (#113)
- A double-click (WM_LBUTTONDBLCLK) or Enter/Space (NIN_KEYSELECT) opens the
  window; a single click does nothing, so its first click no longer reopens it
- The right-click menu is unchanged
- The notice and the user guide say to double-click

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-25 20:04:32 +01:00
nessarandClaude Opus 5.5 98a8a14343 Add Rule #3: tests observe, they don't shape
CI / core (pull_request) Successful in 1m44s
CI / core (push) Successful in 1m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BEKJ9v922udzup4Qn
2026-11-25 19:34:12 +01:00
nessarandClaude Opus 5.5 497c6861a2 Fix what the review of f257c57 found in « En partie » (#109)
CI / core (pull_request) Successful in 1m53s
CI / core (push) Successful in 1m48s
- « En partie » is prepared only while it shows: a statistics change on another tab no longer
  rebuilds it nor reads its 5 Matches, and a tab switch prepares it only when it arrives. The
  banner is dressed once per change.
- A game session that names no champion takes the one its champ select picked, until the
  session says it (the recorded capture has no champion field).
- The 5 Matches are read again whenever the stored Matches change, a Provisional Match
  published included, not only when their count does.
- Clearing the screen keeps the count of its requests: a late answer from a previous game is
  dropped.
- A game the client closed and reconnected to decides its end again at its lobby.
- One rule for « a game's end without a block shows « Défi » once », shared with #129.
- Tab::is_phase and Tab::home_scoped replace the repeated tab lists; match_over and
  leave_live_match hold the LiveMatch instead of Option<Option<u64>>; the 5 Matches' request
  is one RecentQuery; live_match_tab is has_in_game_tab.
- Tests: one fake game client for the page tests; the end-of-game tests read Alice's client;
  the app started during a game; the champ select's pick standing in; the reconnected game;
  « Paramètres » closing without activating the window.
- docs/performance.md lists the `in-game-details` part; docs/interface.md says when the
  screen is prepared, the pick standing in, and the reconnected game.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 18:26:03 +01:00
nessarandClaude Opus 5.5 f257c57b27 Show the Live Match in a tab of its own, « En partie » (#109)
CI / core (pull_request) Successful in 1m50s
- The core reads the champion played in the client's gameflow session
  (champion selections, else the teams, by the summoner's client PUUID) and
  follows the Live Match from one read to the next: it starts with an Arena
  game in progress and lasts through that game's end-of-game screen.
- The follower tells the page the Live Match on each change, before the champ
  select's end, so the end of a champ select that launched a game shows
  « En partie » instead of « Défi », without computing the statistics again.
- « En partie »: the banner with the champion's splash, the Season and the
  count, its tick of the ring lit and the stake (« Un top 1 validerait X :
  88 / 172 », or the day it was validated); « Champion en cours
  d’identification » until the client says it. Under it, the card's sheet and
  the champion's 5 latest Matches of the Season, read at low priority.
- A Live Match is a phase like the champ select: the signed-in Account and the
  current Season, the Account selector greyed, « Paramètres » closed, and a
  minimised or hidden window shown again without the focus, never raised.
- Its end-of-game block ends it and #129 decides the screen; without a block,
  the lobby shows « Défi ». A screen gone with its tab falls back to « Défi ».
- Tests with the simulated client: launch from the champ select, a client met
  in a game, the champion identified late, the end with and without a block,
  a game outside Arena. docs/interface.md and the guide are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BEKJ9v922udzup4Qn
2026-11-25 17:58:01 +01:00
nessarandClaude Opus 5.5 dcb7ac303c Show augments as item-like slots with the game's coloured icons (#135)
CI / core (pull_request) Successful in 1m57s
CI / core (push) Successful in 1m49s
- The recap draws six augment slots per player, like the seven item slots:
  the augments taken, then empty slots, so the lines read in columns; the
  name moves to the bubble.
- The catalog takes CommunityDragon's large augment icon (coloured by rarity)
  instead of the small white glyph, shrunk to 64 px at download.
- catalog.json gets a format number: a cache from before is read again from
  the sources at the same patch and its augment icons downloaded again.
- A first download tells the page every 100 icons, so icons show as they come
  instead of after the whole pass.
- The icon download tests move to tests/game_data/icons.rs (Rule #2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BEKJ9v922udzup4Qn
2026-11-25 13:45:00 +01:00
nessarandClaude Opus 5.5 bf9ea585d2 Restore the missing slot bubble and drop test-only code from the recap (#135)
CI / core (pull_request) Successful in 1m43s
- A slot the source does not give keeps its one-word bubble (« Indisponible »,
  « En attente » in a Provisional Match), registered only while visible.
- bubble::Visible takes a Bubble (described or a word); the tests' selectors are
  set by the recap with item_selector / augment_selector, no #[cfg(test)] code.
- Name, description and icon travel as one Described in slots, chips and the
  damage seen lines; the old per-field catalog accessors are gone.
- A catalog list needs 9 entries in 10 named to replace the cache.
- An unknown {{…}} reference in an augment summary becomes « ? ».
- A panic of the catalog worker is reported as Crashed; spawn_game_catalog
  moves to the test fake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BEKJ9v922udzup4Qn
2026-11-25 10:41:31 +01:00
nessar a4a2a51670 Keep incomplete catalogs and offscreen tooltips out of the recap (#135)
CI / core (pull_request) Successful in 1m39s
Reject patch lists without any names before writing the cache and retry unusable caches at the same version. Scope visible tooltips to their player so inactive item slots need no tooltip state.
2026-11-25 09:13:08 +01:00
nessar bb20a1f853 Address French catalog and tooltip review findings (#135)
CI / core (pull_request) Successful in 1m55s
2026-11-25 09:00:37 +01:00
nessar 9daea4f4ef v1 2026-11-25 09:00:37 +01:00
nessar 544bcfbb86 codex agent
CI / core (push) Successful in 1m50s
2026-11-25 01:18:23 +01:00
nessar fa51ef49d2 perf agent
CI / core (push) Successful in 1m50s
2026-11-25 01:16:39 +01:00
nessarandClaude Opus 5.5 d2ff74a383 Draw the recap's statistics as bars, colour the list's Placements
CI / core (pull_request) Successful in 1m51s
CI / core (push) Successful in 1m46s
- A player's details draw bars: the two damage rows as one bar split by type (physical, magic,
  true), the total beside it and each type in a legend under it; Protection, Or and Contrôle
  as one bar per measure, full for the best player of the Match. One absent type leaves the
  split bar empty. The fills are written with the recap, never computed on screen.
- Each folded player line draws its damage to champions as a bar as long as its share of the
  Match's best total, split by type; in one neutral colour while the types are not given
  (a Provisional Match).
- The list of « Parties » colours each Placement: gold for a top 1, the palette's success ink
  for another Win, its danger ink otherwise.
- The details' rendering moves to details_view.rs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:27:40 +01:00
nessarandClaude Opus 5.5 af873288e2 Record the French game catalog decision, name Items and Augments (#131)
ADR-0007 (proposed until #131 ships): the names, icons and descriptions of Items and Augments
will come in French from Data Dragon and CommunityDragon, not from the client, which serves
its own locale and gives no Augment description. The glossary names Item (Objet) and Augment
(Amélioration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:27:40 +01:00
nessarandClaude Opus 5.5 c90db5ea67 Show the history's Account in the greyed selector of « Parties »
CI / core (pull_request) Successful in 1m51s
A pinned Account no longer chooses the list of « Parties »: the selector says whose Matches
they are, and gives the pinned Account back on the other screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3AqGyEbouXkQJJdnQT
2026-11-24 09:28:49 +01:00
nessarandClaude Opus 5.5 78ed351601 Fix what the review of 1192c13 found in « Parties » (#123, #124, #127, #129)
- A block is written as its event arrives, from the wait for client events, with the Riot ID
  and client PUUID signed in at that moment: it builds the Match of that Account whoever signs
  in before a round gets to it.
- A block whose mode nothing tells waits instead of losing its text; only a game known to be
  of another mode is dropped.
- The follower remembers only the game in progress a Provisional Match stands for, and looks
  at it only when that game has just ended (follow/game_end.rs).
- A Match no Season holds is still reported: its block opens its recap.
- The client leaving an Arena game is told to the page once: without a block, or with the
  preference off, it shows the Challenge; a block decided on is not undone.
- « Parties » lists the Account signed in to the client, never the pinned one.
- Widening the Season for a new Match recomputes the statistics on the worker, to the Match's
  own Season.
- A corrected Placement follows the unfolded player, or folds the details.
- One Death Recap read at a time; only the latest waits, and leaving the screen drops it.
- A narrow window builds its closed list no more and gives its portraits back.
- The game data cache is keyed by the client's locale too, and an icon whose route changed is
  downloaded again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3AqGyEbouXkQJJdnQT
2026-11-24 09:27:38 +01:00
nessarandClaude Opus 5.5 1192c13830 Name things as the glossary does, reuse the core's Season periods
CI / core (pull_request) Successful in 1m46s
« En attente » is AWAITED, the block's PUUID is the client's; the filters
of « Parties » use the core's period of a Season instead of a copy; the
list view joins the cached views in docs/performance.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 05:19:27 +01:00
nessarandClaude Opus 5.5 d4cdfd9670 Fix what the final review found in « Parties » (#124, #125, #127, #128, #129)
One timeline download per Match even when the queue and an opened recap
ask together; a Death Recap matched with an outdated catalog is matched
again; end-of-game blocks keep their text only while their Match may still
need it; block platforms are upper case; unbuilt blocks are retried during
their window, then only after a sync; the queue thread no longer wakes each
minute; auto-open widens Season and Format when they hide the new Match;
clearer mitigation and control-score labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 05:14:55 +01:00
nessarandClaude Opus 5.5 7396e87291 Open the new Match's recap when its end-of-game block arrives (#129)
« Parties » shows the Provisional Match from any tab and « Paramètres »
closes, without restoring, raising or focusing the window. A setting,
on by default, keeps the Challenge instead. Root tests no longer start the
game catalog thread, which made a settings test flaky.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 05:00:05 +01:00
nessarandClaude Opus 5.5 7f56f090aa Show the damage seen in Death Recaps in a player's details (#128)
By item and augment, then « Autres effets »; « En attente » for a
Provisional Match, « Indisponible » when Riot refuses, « Réessayer » after
a passing failure. A followed Match's timeline is fetched by a background
queue, an older one's on its first opening.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 04:45:58 +01:00
nessarandClaude Opus 5.5 7575ab0165 Show item and augment names and icons in the recap (#124, #127)
The catalog is loaded from its disk cache at launch and refreshed in the
background when the client appears; unknown ids keep the neutral look.
Provisional Matches get tests for « Provisoire », « En attente » and their
silent publication. Reopening « Parties » no longer re-reads an unchanged
list, and a failed recap is decoded again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 04:25:22 +01:00
nessarandClaude Opus 5.5 4c68fd2814 Filter « Parties » by Season, Format, Placement and champion (#126)
Season and Format are the Statistics page's own selectors; Placement offers
« Tous · Top 1 · Victoires » and the search is the home's, aliases included.
Filtering works on the rows already loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:37:42 +01:00
nessarandClaude Opus 5.5 61bd6114ff Keep every end-of-game block, bound Provisional look-ups (#127, #128)
A block is written as received before any Match is built from it, and its
build is retried until it works, so an unverified key name loses nothing.
Riot is asked for a Provisional Match during its pending window, then only
by syncs; a sync that publishes one queues its Death Recap. Arena items
carry the 22 prefix in the exceptions, and a block's own platform names
its Match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:33:52 +01:00
nessarandClaude Opus 5.5 a4f2069f87 Unfold a player's details in the Match Recap (#125)
Damage dealt and taken by type, mitigation, heals and shields on allies,
gold and crowd control, as the source gives them, built once per recap and
only drawn for the player unfolded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:28:08 +01:00
nessarandClaude Opus 5.5 beb5e5037b Add the « Parties » tab: the Account's Matches and their recap (#123)
Newest first, the most recent chosen at each opening; teams by Placement
with the Account highlighted, and « Indisponible » where the source says
nothing. The list is its own virtualized view; below 900 px it goes behind
a button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:20:35 +01:00
nessarandClaude Opus 5.5 9999a68be5 Keep the Death Recaps of a Match and sum them by item and augment (#128)
Only the victimDamageReceived entries of the Match-V5 timeline are kept,
fetched after a followed Match is published or when an older one is first
opened; a refusal is remembered, a passing failure is not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:11:22 +01:00
nessarandClaude Opus 5.5 71a3b28a10 Cache the client's item and augment names and icons (#124)
A game data catalog read from /lol-game-data in the client's language, kept
on disk and renewed once per game version, so recaps stay readable with the
client closed. It keeps each augment's augmentNameId for the Death Recap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:05:04 +01:00
nessarandClaude Opus 5.5 6baa482d17 Count a Provisional Match from the client's end-of-game block (#127)
The block is kept as soon as its event arrives and stored as a Match flagged
provisional under the Account that played; it counts at once (ADR 0006) and
Riot's published Match replaces it silently, looked up until it appears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:00:57 +01:00
nessarandClaude Opus 5.5 9b02c3eab7 Make « Sélection » a phase tab beside « Défi » (#108)
Entering an Arena champ select adds the tab and shows it from anywhere; the
Challenge and Statistics stay reachable during it, and coming back shows the
hand at rest. Its end removes the tab and shows the Challenge, the hand
leaving first when « Sélection » was in front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:59:14 +01:00
nessarandClaude Opus 5.5 665f129da0 Open « Statistiques » from the Challenge banner, not the top bar (#107)
A « Statistiques › » link under the counter opens it with the usual veil;
« ‹ Défi » and the « Défi » tab bring the Challenge back, by mouse or keyboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:47:04 +01:00
nessarandClaude Opus 5.5 4ce9d02169 Decode a stored Match into its Match Recap (#123)
Teams by Placement, the Account flagged, every participant's values as the
source gives them: absent stays None, an explicit 0 stays 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:47:04 +01:00
nessarandClaude Opus 5.5 b09327ed1c Name Provisional Matches and the Death Recap, record why they count (#22)
CI / core (push) Successful in 1m38s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:59:49 +01:00
nessarandClaude Opus 5.5 1e44baa157 Bring a covered window to the front too when an Arena champ select starts (#118)
CI / core (pull_request) Successful in 1m40s
CI / core (push) Successful in 1m37s
A window already shown was left alone, so one open behind Chrome stayed
hidden at the start of a champ select. Every window state now gets the same
raise, still without activation and once per entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:36:53 +01:00
238 changed files with 27437 additions and 1396 deletions

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
---
name: perf-guard
description: "Reviews Arena Tracker code against Rule #1 (fluid and light) and flags suboptimal code with its estimated cost, the trigger that pays it and the budget it eats. Use after changing code under crates/ (before committing or opening a PR), on a branch or commit range, or to audit a given file or module. Read-only; never edits code, never runs probes or builds."
tools: Read, Grep, Glob, Bash
---
You guard Rule #1 of Arena Tracker: the app stays as fluid and light as possible, it never feels slow and never makes the computer feel slow, and this comes before features. Your job is to find code that costs more than it needs to and to put a price on it, so the author can decide with numbers. You are a reviewer, not a zealot: a finding without a real cost is noise, and noise makes the real findings easier to ignore.
## Read first
- `CLAUDE.md` (Rule #1 and its view-boundary rule).
- `docs/performance.md`: the budgets table, their **current values** (headroom), "Measuring" (cached views, structural tests, image caches) and "Animations and splashes".
- `docs/adr/0004-reduce-rendering-cost-instead-of-patching-gpui.md`.
Read them every run: the budgets and current values change at each release benchmark (ratchet).
## Scope
- No argument: the changes on the current branch, `git diff $(git merge-base HEAD develop)...HEAD` plus uncommitted changes (`git diff HEAD`). If the branch is `develop` itself, the uncommitted changes only; if there are none, say so and stop.
- A range, commit or PR branch: that diff.
- A file, module or area: audit that code as it stands, not only a diff.
Review changed lines, but read enough of the surroundings to know **how often** they run: who calls this function, from which render, which event handler, which thread. Bash is for `git` and read-only inspection (`git diff`, `git log`, `git show`, `wc`, `rg`); never build, run tests, run probes or benchmarks, and never modify a file.
## What the app's hot paths are
Cost is cost × frequency. Know the frequencies:
- **A window move refreshes the whole window and bypasses every cached view** (GPUI `bounds_changed`): every view's `render` runs, at the display rate (60 Hz on the reference machine, 240 Hz on the manual checks one). Anything in a `render` is therefore per frame in the worst case, cached view or not.
- **Hover, wheel, scroll, drag, resize**: one frame each, up to the display rate. Hovering the champion table or a card grid, scrolling the home grid or a champ select are the measured interactions.
- **Animation frames** (`request_animation_frame`, `on_next_frame`): every frame while the motion runs; must be none at rest.
- **Idle, window visible**: the UI thread already wakes ~60–67 times per second for GPUI's vsync; any extra wake-up, timer or poll the app adds is pure cost against budget 2.
- **Minimised / hidden**: nothing must render, nothing must wake for the app's own sake.
- **Per event**: follower round, champ select update, Match imported, statistics recomputed, tab change, settings change. Moderate frequency, but a champ select can update several times per second.
- **Once**: start, first import, a click on a button. Cold unless very large.
Data sizes to multiply by: about 170 champions (one card / one table row each), a few hundred Matches per Account (466 in the benchmark), 175 portraits and as many splashes on disk.
## Budgets and headroom (check the current table, these are from the 1.0 benchmark)
1. Interactions: ≤ 6 ms per frame at p99; measured 5.3–5.9 ms. **Headroom is a few hundred µs**, so 0.1 ms per frame on a hot path matters.
2. Idle visible CPU: ≤ 1.1 % of a core; measured 0.88–1.08 %. One extra wake-up per second is visible; a 60 Hz timer breaks it.
3. Minimised ≤ 1.1 %, hidden ≤ 0.35 %, no rendering.
4. Memory, full page loaded: ≤ 150 MB working set; measured 146–149 MB. **A few MB is the whole margin.**
5. Background work: low-priority threads, never more than one core.
## What to flag
Flag code that does avoidable work on a path that runs often, or holds memory or threads it does not need. Typical shapes here:
- **Render paths** (`render`, `render_*` functions, element builders, `prepaint`/`paint` closures): sorting, filtering, searching or computing statistics; cloning collections or `String`s per row/card; `format!` of values that only change on an event; building data structures (`HashMap`, `Vec`) that could be prepared when the data changes; O(n) or O(n²) over champions/Matches per frame; layout or text shaping work that could be cached.
- **Invalidation**: `cx.notify()` on a wide view for a change only a child shows; state stored where a change forces the page (or a cached view's parent) to render; a cached view whose size depends on its content (it cannot stay cached), or whose cache key changes per frame (bounds, opacity, scroll offset: see the veil vs. slide decision).
- **View boundaries**: a new view without a reason (owns state that changes on its own, or is a cached view with a structural test). A view that is not cached saves nothing and costs sync.
- **Missing structural test**: a change that relies on a cached view (or on "this does not render / build / sort / compute on hover") without a test guarding it, as `docs/performance.md` requires.
- **Polling and timers**: a loop, `Timer::after`, sleep or periodic task where an event, a channel or a Windows message exists; frames asked for at rest; an animation that keeps asking once over, or runs while hidden, minimised or behind another screen; ignoring `reduce_motion`.
- **UI thread blocking**: file or network IO, image decoding, JSON parsing, statistics computation on the UI thread; a lock held across slow work that the UI thread waits on.
- **Background work**: a thread not started through `spawn_guarded` / `lower_priority`, short work on GPUI's pool without `BelowNormal` or `Priority::Low`, parallelism that can take more than one core, busy-waiting, retries without backoff.
- **Memory**: images loaded through GPUI's app-wide cache instead of the grid's own `CardImages`; portraits or splashes kept for cards not painted or screens not shown; more than two splashes decoded; buffers sized by the whole history when only a page of it is shown; caches with no bound or no release; big clones kept alive by closures.
- **Allocation churn** on hot paths: `collect()` into a temporary only to iterate it, `to_string()`/`clone()` where a borrow, an `Arc`, a `SharedString` or an index would do.
Never suggest modifying GPUI or gpui-component (ADR-0004): the lever is the app's own rendering cost.
## What not to flag (stay reasonable)
- Code that runs once or once per user click, unless it costs ≳ 1 ms on the UI thread or is visible as a hitch.
- Per-frame costs well under 1 µs that are not multiplied by rows, cards or Matches. A single small `clone` in a render is fine.
- Tests, test fixtures, `--features profile` instrumentation, error paths, logging that only runs on failure.
- Rewrites that make the code notably harder to read for a gain you cannot express in µs per frame, wakes per second or MB.
- Speculative "might be slow" without a trigger: if you cannot say when it runs and how often, investigate more or drop it.
- Style, naming, Rule #2 or correctness issues unrelated to cost: other reviewers handle them.
When in doubt, keep the finding but rate it `minor` and say what would make it matter.
## Estimating the cost
Every finding carries a number, even a rough one, with the arithmetic shown. Order-of-magnitude figures for a Ryzen 5 7640U in a release build (estimates, say so):
- heap allocation + free: ~20–50 ns; small `String` `format!`: ~100–200 ns; `HashMap` insert: ~30–50 ns.
- sorting 170 items by a cheap key: ~5–15 µs; by a key that allocates (e.g. lowercase names): ~30–60 µs.
- cloning a `Vec` of a few hundred structs with `String` fields: ~10–50 µs.
- one GPUI element built and laid out (div with a few style calls): on the order of 1 µs; a card or table row of a dozen elements: ~10–20 µs; 170 of them: ~2–3 ms, i.e. most of budget 1.
- a thread wake-up: ~5–85 µs of CPU on the reference machine (see budget 3 notes); 60 per second ≈ 0.3 % of a core.
- RGBA image in memory: width × height × 4 bytes (128 × 128 portrait ≈ 64 KB; a splash about 1215 × 717 ≈ 3.5 MB), plus its copy in the GPU atlas, which is system memory on the reference iGPU.
- decoding a JPEG/PNG splash: tens of ms, never on the UI thread.
Express cost in the unit of the budget it hits: **µs or ms per frame** (and at which trigger: move, hover, scroll, animation), **wake-ups per second / % of a core** at idle, **MB held** and when, **cores** for background work. Then compare with the headroom above. Give a confidence (high / medium / low) and say what measurement would settle it (which probe or `ARENA_TRACKER_HIDE` part), without running it.
## Report
Write in the user's language (French if they wrote in French). Lead with a one-line verdict: clean, or N findings with the worst one named.
Then findings, most costly first:
```
### [blocker|should-fix|minor] Short title
`path/to/file.rs:123`. Trigger: <when it runs, how often>. Budget <n>.
Cost: <estimate with arithmetic> (confidence: high|medium|low).
Why it is avoidable: <one or two sentences>.
Fix: <the lightest change that removes the cost; a short code sketch if it helps>.
```
- **blocker**: likely breaks a budget given the current headroom, or breaks a hard rule (rendering while hidden, frames at rest, polling where an event exists, UI-thread IO/decoding, background thread at normal priority, image through GPUI's app-wide cache, cached view relied on without a structural test).
- **should-fix**: a measurable cost on a hot path (≳ 10 µs per frame, ≳ 1 wake per second, ≳ 1 MB held needlessly), cheap to remove.
- **minor**: real but small; worth taking if the code is touched anyway.
End with a short **Checked, fine** list: the hot spots you looked at and judged acceptable, with one line each on why (e.g. "`sort_cards` in `card_order.rs`: runs on statistics change, not per frame"). It shows the review covered them and calibrates the findings.
If you find nothing worth flagging, say so plainly; do not invent minor findings to fill the report.
Submodule .claude/worktrees/22-parties added at c90db5ea67.
+8
View File
@@ -0,0 +1,8 @@
# Codex wrapper for the perf-guard reviewer. The instructions live in one place,
# .claude/agents/perf-guard.md, shared with Claude Code: edit them there.
name = "perf-guard"
description = "Reviews Arena Tracker code against Rule #1 (fluid and light) and flags suboptimal code with its estimated cost, the trigger that pays it and the budget it eats. Use after changing code under crates/, on a branch or commit range, or to audit a given file or module. Read-only."
developer_instructions = """
Read .claude/agents/perf-guard.md at the repository root, skip its YAML frontmatter, and follow the rest exactly: it is your full brief.
You are read-only: never modify a file, never build, run tests, probes or benchmarks. Use the shell only for git and read-only inspection.
"""
+7
View File
@@ -0,0 +1,7 @@
# Only what the relay's image needs goes into the build context: never .env nor target/.
*
!Cargo.toml
!Cargo.lock
!crates/
crates/*/target/
!site/
+21 -1
View File
@@ -1,4 +1,5 @@
# Only the core crate is checked: the app crate (GPUI) only builds on Windows (ADR-0003).
# The core and the relay are checked, each in its own job: the app crate (GPUI) only builds on
# Windows (ADR-0003). Both jobs are required checks for merging (docs/publication.md).
# Betas of develop and stables of main are published from the build PC once these checks pass (docs/publication.md).
name: CI
@@ -35,3 +36,22 @@ jobs:
- name: Publication tests
run: python3 scripts/test_publish.py
relay:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust stable (rustfmt, clippy)
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --component rustfmt,clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Format
run: cargo fmt -p arena-tracker-relay --check
- name: Clippy
run: cargo clippy -p arena-tracker-relay --all-targets --locked -- -D warnings
- name: Tests
run: cargo test -p arena-tracker-relay --locked
+1
View File
@@ -2,3 +2,4 @@
*.local.toml
.env
__pycache__/
.scratch/
+7
View File
@@ -18,6 +18,13 @@ When adding behavior or tests would grow a Rust file and leave it above 500 line
- Group integration tests by behavior in the package's top-level `tests/` directory and exercise the public API.
- When documenting a runnable API example, use a Rust code block in the item's `///` comments so `cargo test` checks it.
## Rule #3: tests observe, they don't shape
Production code does not exist to satisfy a test. Tests go through the same paths production uses; when a test needs a way in, that is a design seam with a production meaning (an injected clock, a trait with a real implementation), not a test hook.
- No `cfg(test)` / `cfg!(test)` branches inside production logic, no flags or parameters only tests set, no visibility widened only for tests.
- Exception: passive instrumentation under `#[cfg(test)]` (counters, recorded events) that guards a Rule #1 structural test, never read by production code and never changing its behaviour.
## Agent skills
### Issue tracker
+20
View File
@@ -16,6 +16,22 @@ _Avoid_: Current game, ongoing match, game in progress
The available statistics for a Match and its participants.
_Avoid_: Match report
**Provisional**:
The state of a Match from the player's exit until Riot publishes its result; its Placement and statistics may still change, and it already counts with its provisional Placement.
_Avoid_: Pending, temporary, unconfirmed
**Item**:
Something a champion buys during a Match for stats or effects; the Match keeps those held at its end.
_Avoid_: Equipment, gear
**Augment**:
A power a champion picks between the rounds of an Arena Match, of a given rarity; the Match keeps those picked.
_Avoid_: Perk, upgrade, buff
**Death Recap**:
The game's breakdown of the damage a champion received before an elimination, by source and effect; the only source of damage by item or augment, so damage dealt to a champion who survives is never attributed.
_Avoid_: Kill recap, damage log
**Format**:
A variant of Arena with its own team structure and rules, such as Arena 3x6 or Bravery Arena; it filters statistics but does not split the Challenge.
_Avoid_: Mode, type, queue
@@ -92,6 +108,10 @@ The interface is in French. Each glossary term has one French word in user-facin
| Match | Partie |
| Live Match | Partie en cours |
| Match Recap | Récapitulatif de partie |
| Provisional | Provisoire |
| Death Recap | Récap de mort |
| Item | Objet |
| Augment | Amélioration |
| Challenge | Défi |
| Mark | Marque |
| Mastery Points | Points de maîtrise |
Generated
+41
View File
@@ -227,6 +227,7 @@ dependencies = [
"gpui-kit",
"gpui-pre",
"image",
"log",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
@@ -238,6 +239,7 @@ version = "1.1.0"
dependencies = [
"base64 0.23.1",
"image",
"log",
"ring",
"rusqlite",
"rustls",
@@ -249,6 +251,15 @@ dependencies = [
"ureq",
]
[[package]]
name = "arena-tracker-relay"
version = "1.1.0"
dependencies = [
"log",
"tiny_http",
"ureq",
]
[[package]]
name = "arg_enum_proc_macro"
version = "0.3.4"
@@ -293,6 +304,12 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -926,6 +943,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -3170,6 +3193,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -6910,6 +6939,18 @@ dependencies = [
"strict-num",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "tinystr"
version = "0.8.5"
+3 -2
View File
@@ -1,9 +1,10 @@
[workspace]
resolver = "3"
members = ["crates/core", "crates/app"]
default-members = ["crates/core"]
members = ["crates/core", "crates/app", "crates/relay"]
default-members = ["crates/core", "crates/relay"]
[workspace.package]
edition = "2024"
rust-version = "1.98"
version = "1.1.0"
license = "AGPL-3.0-or-later"
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+9
View File
@@ -61,3 +61,12 @@ cargo test
- À chaque pull request et à chaque push sur `main`, un workflow Gitea Actions (`.gitea/workflows/ci.yml`) vérifie le formatage (`cargo fmt --check`), lance le linter (`cargo clippy`, avertissements traités comme des erreurs) et exécute les tests (`cargo test`) du coeur `arena-tracker-core`, avec `--locked` : un `Cargo.lock` non à jour fait échouer la CI.
- La crate applicative (GPUI) n'est pas compilée en CI, car elle ne se compile que sous Windows (ADR-0003). La CI ne compile ni ne publie l'exécutable Windows.
- Le workflow nécessite un runner Linux (`act_runner`) enregistré sur l'instance Gitea.
## Licence
Arena Tracker est un logiciel libre sous licence [GNU AGPL 3.0](LICENSE) ou toute version ultérieure (`AGPL-3.0-or-later`). Elle couvre aussi l'usage par le réseau : qui fait tourner une version modifiée du service intermédiaire (`crates/relay`) doit en publier le code.
Restent sous leur propre licence :
- les polices Inter et Unbounded (SIL Open Font License, `crates/app/assets/*-LICENSE.txt`) ;
- les images, noms et données de League of Legends (captures du site, portrait des tests, ce que l'application télécharge) et le certificat `riotgames.pem` : propriété de Riot Games. Arena Tracker n'est pas approuvé par Riot Games et ne reflète pas les opinions de Riot Games ni de quiconque officiellement impliqué dans la production ou la gestion des propriétés de Riot Games. Riot Games et toutes les propriétés associées sont des marques commerciales ou des marques déposées de Riot Games, Inc.
+2
View File
@@ -3,6 +3,7 @@ name = "arena-tracker"
edition.workspace = true
rust-version.workspace = true
version.workspace = true
license.workspace = true
[features]
profile = ["gpui-kit/profiler"]
@@ -11,6 +12,7 @@ profile = ["gpui-kit/profiler"]
arena-tracker-core = { path = "../core" }
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
gpui-kit = "=0.9.1"
log = "0.4"
# Decodes the banner's splash at low priority (the same version as GPUI's and the core's).
image = { version = "0.25.10", default-features = false, features = ["jpeg"] }
+50
View File
@@ -0,0 +1,50 @@
//! The app's asset source: the kit's default bundle, plus the one Lucide icon it does not
//! embed (`chart-line`). `AllAssets` would embed the whole catalog for this one icon.
use std::borrow::Cow;
use gpui_kit::{AssetSource, Result, SharedString};
gpui_kit::assets::icon_assets!(ExtraIcons, [ChartLine]);
pub struct Assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = ExtraIcons.load(path)? {
return Ok(Some(bytes));
}
gpui_kit::assets::Assets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = gpui_kit::assets::Assets.list(path)?;
paths.extend(ExtraIcons.list(path)?);
paths.sort();
paths.dedup();
Ok(paths)
}
}
#[cfg(test)]
mod tests {
use super::*;
const CHART_LINE: &str = "icons/chart-line.svg";
#[test]
fn serves_chart_line_and_delegates_the_rest() {
assert!(matches!(Assets.load(CHART_LINE), Ok(Some(_))));
use gpui_kit::component::{IconName, IconNamed as _};
assert_eq!(gpui_kit::assets::IconName::ChartLine.path(), CHART_LINE);
let path = IconName::Settings.path();
assert!(matches!(Assets.load(&path), Ok(Some(_))));
assert!(
Assets
.list("icons/")
.unwrap()
.iter()
.any(|p| p == CHART_LINE)
);
}
}
+2 -2
View File
@@ -237,8 +237,8 @@ impl Card {
}
/// The sheet's figures for the Season, all Formats; « — » where there is none (no Season, or no
/// Match). The date is only there once the champion is Completed.
fn sheet_lines(row: &ChampionRow) -> Vec<(&'static str, SharedString)> {
/// Match). The date is only there once the champion is Completed. « En partie » shows them too.
pub fn sheet_lines(row: &ChampionRow) -> Vec<(&'static str, SharedString)> {
let challenge = row.challenge;
let count = |n: Option<usize>| -> SharedString {
n.map_or_else(|| NONE.into(), |n| n.to_string().into())
+23
View File
@@ -0,0 +1,23 @@
//! A click anywhere in a text field's frame gives it the keyboard.
//!
//! gpui-component's `Input` tracks a focus handle of its own on the frame, apart from the
//! editor's: a click in the padding or the border focused the frame, and typing wrote nothing.
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::*;
/// `input` in a wrapper that focuses `state` on a left click the editor did not take (the
/// padding, the border). The text line and the buttons run first and keep their own click, but
/// the field's own buttons (the clear cross, the mask toggle) do not stop the event, so a click
/// on one also focuses the field. The wrapper does nothing once the editor has the focus. Size
/// the wrapper, not the `Input`.
pub fn input_frame(state: &Entity<InputState>, input: Input) -> Div {
let state = state.clone();
div()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !state.read(cx).focus_handle(cx).is_focused(window) {
state.update(cx, |state, cx| state.focus(window, cx));
}
})
.child(input)
}
+46
View File
@@ -0,0 +1,46 @@
//! The application log's start and end (#142): the file is `logs\arena-tracker.log` under the
//! data folder, also on stderr in debug builds. Nothing is lost on a way out of `main`.
use arena_tracker_core::{Config, data_dir, init_journal};
use crate::release::{self, channel};
use crate::worker::lower_priority;
/// Opens the log with its launch line. A log that cannot be opened is not worth stopping for.
pub fn start() -> Flush {
if let Some(dir) = data_dir() {
let preferences = Config::load_or_default(&dir.join("config.toml"))
.map(|config| config.preferences)
.unwrap_or_default();
let channel = format!("{:?}", channel(preferences)).to_lowercase();
// A dev build must not look like the stable release.
let version = release::VERSION.unwrap_or(concat!(env!("CARGO_PKG_VERSION"), "-dev"));
if let Err(error) = init_journal(
&dir,
cfg!(debug_assertions),
version,
&channel,
lower_priority,
) {
eprintln!("Failed to open the log: {error}");
}
}
Flush
}
/// Writes what is still buffered when it is dropped, at the end of `main`.
pub struct Flush;
impl Drop for Flush {
fn drop(&mut self) {
log::logger().flush();
}
}
/// The app quits through `cx.quit()`: what is buffered is written before it does.
pub fn flush_on_quit(cx: &gpui_kit::App) {
cx.on_app_quit(|_| {
log::logger().flush();
async {}
})
.detach();
}
+136
View File
@@ -0,0 +1,136 @@
//! The player's wall clock: a Match's start as the date and time Windows shows, with the
//! daylight saving time in force on that day, not today's.
use arena_tracker_core::Date;
/// A day and a time of day on the player's clock.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalTime {
pub date: Date,
pub hour: u8,
pub minute: u8,
}
impl LocalTime {
/// The UTC day and time of that instant: the clock where Windows cannot tell.
pub fn utc(epoch_ms: i64) -> LocalTime {
const MS_PER_MINUTE: i64 = 60_000;
let minutes = epoch_ms.rem_euclid(86_400_000) / MS_PER_MINUTE;
LocalTime {
date: Date::from_ms(epoch_ms),
hour: (minutes / 60) as u8,
minute: (minutes % 60) as u8,
}
}
}
/// That instant on the player's clock.
pub fn local_time(epoch_ms: i64) -> LocalTime {
#[cfg(windows)]
if let Some(local) = windows::local_time(epoch_ms) {
return local;
}
LocalTime::utc(epoch_ms)
}
#[cfg(windows)]
mod windows {
use super::LocalTime;
use arena_tracker_core::Date;
#[repr(C)]
#[derive(Default)]
struct FileTime {
low: u32,
high: u32,
}
#[repr(C)]
#[derive(Default)]
struct SystemTime {
year: u16,
month: u16,
day_of_week: u16,
day: u16,
hour: u16,
minute: u16,
second: u16,
milliseconds: u16,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn FileTimeToSystemTime(file_time: *const FileTime, system_time: *mut SystemTime) -> i32;
fn SystemTimeToTzSpecificLocalTime(
time_zone: *const core::ffi::c_void,
universal: *const SystemTime,
local: *mut SystemTime,
) -> i32;
}
/// Milliseconds from 1601-01-01, where Windows counts from, to 1970-01-01.
const EPOCH_FROM_1601_MS: i64 = 11_644_473_600_000;
/// `None` when Windows refuses the instant.
pub(super) fn local_time(epoch_ms: i64) -> Option<LocalTime> {
let ticks = u64::try_from(epoch_ms.checked_add(EPOCH_FROM_1601_MS)?)
.ok()?
.checked_mul(10_000)?;
let file_time = FileTime {
low: ticks as u32,
high: (ticks >> 32) as u32,
};
let (mut universal, mut local) = (SystemTime::default(), SystemTime::default());
// SAFETY: both structures are the Win32 layouts, alive for the calls; a null time zone
// is the one in force.
let converted = unsafe {
FileTimeToSystemTime(&file_time, &mut universal) != 0
&& SystemTimeToTzSpecificLocalTime(core::ptr::null(), &universal, &mut local) != 0
};
converted.then(|| LocalTime {
date: Date {
year: i32::from(local.year),
month: local.month as u8,
day: local.day as u8,
},
hour: local.hour as u8,
minute: local.minute as u8,
})
}
}
#[cfg(test)]
mod tests {
use super::{LocalTime, local_time};
use arena_tracker_core::Date;
#[test]
fn the_utc_clock_splits_the_instant() {
// 2026-11-15 17:29:12 UTC.
let time = LocalTime::utc(1_794_763_752_767);
assert_eq!(
time,
LocalTime {
date: Date {
year: 2026,
month: 11,
day: 15
},
hour: 17,
minute: 29,
}
);
}
#[test]
fn the_local_clock_is_whole_minutes_away_from_utc() {
// Whatever the machine's time zone: at most 14 hours away, by whole quarter hours.
let at = 1_794_763_752_767;
let local = local_time(at);
let minutes = |t: LocalTime| {
(Date::start_ms(&t.date) / 60_000) + i64::from(t.hour) * 60 + i64::from(t.minute)
};
let shift = minutes(local) - minutes(LocalTime::utc(at));
assert!(shift.abs() <= 14 * 60 && shift % 15 == 0, "{shift}");
}
}
+97 -18
View File
@@ -1,5 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod assets;
mod banner_art;
mod card;
mod card_grid;
@@ -7,6 +8,9 @@ mod card_images;
mod card_lift;
mod card_order;
mod champion_table;
mod input_frame;
mod journal;
mod local_time;
mod logon;
mod minimized;
mod motion;
@@ -27,17 +31,17 @@ mod worker;
use std::{ops::ControlFlow, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, Preferences, RiotApi, Tracker, data_dir, default_seasons,
load_seasons,
Config, DataDragon, GameData, LeagueClient, Preferences, RiotApi, Tracker, data_dir,
default_seasons, load_seasons,
};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::*;
use gpui_kit::*;
use page::{ChampionSortChosen, Launch, Page};
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::{Msg, spawn_follower};
use worker::{CatalogRefresh, Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
enum Screen {
@@ -53,6 +57,7 @@ struct RootView {
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
catalog_refresh: Option<Arc<CatalogRefresh>>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
@@ -61,6 +66,9 @@ struct RootView {
blank: bool,
_form_events: Subscription,
_champ_select: Subscription,
_recap: Subscription,
_live_match: Subscription,
_settings: Subscription,
_sort: Subscription,
}
@@ -68,6 +76,7 @@ impl RootView {
fn new(setup: Setup, hidden: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
let Setup {
tracker,
game_data,
riot_id,
notice,
store,
@@ -75,15 +84,17 @@ impl RootView {
// Without a key the page still shows what is stored; only a true first launch (no key
// and nothing stored) has nothing to show, so the key form stands in for the page.
let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty();
let champion_sort = store.preferences().champion_sort;
let preferences = store.preferences();
let (tx, rx) = unbounded();
let catalog_refresh = game_data.map(|data| CatalogRefresh::start(data, tx.clone()));
let page = cx.new(|cx| {
Page::new(
tracker.clone(),
Launch {
notice,
following: !first_launch,
champion_sort,
champion_sort: preferences.champion_sort,
open_recap_at_match_end: preferences.open_recap_at_match_end,
},
rx,
tx.clone(),
@@ -91,7 +102,7 @@ impl RootView {
cx,
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let form = cx.new(|cx| KeyForm::new(store, tracker.clone(), first_launch, window, cx));
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, window, cx| {
match event {
@@ -99,13 +110,30 @@ impl RootView {
// Nothing is imported before a key exists: the follower starts now.
let (tracker, riot_id) =
(this.tracker.clone(), this.fallback_riot_id.clone());
spawn_follower(tracker, riot_id, this.tx.clone());
spawn_follower(
tracker,
riot_id,
this.catalog_refresh.clone(),
this.tx.clone(),
);
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
// « Paramètres » stays open.
KeyEvent::AccountDeleted(puuid) => {
return this
.page
.update(cx, |page, cx| page.account_deleted(puuid, window, cx));
}
// Only the title bar changes.
KeyEvent::UpdateReady => return cx.notify(),
KeyEvent::Preferences(preferences) => {
let open = preferences.open_recap_at_match_end;
return this
.page
.update(cx, |page, _| page.set_open_recap_at_match_end(open));
}
}
this.show_page(window, cx);
});
@@ -118,7 +146,8 @@ impl RootView {
&& let Some(hwnd) = tray::window_hwnd(window)
{
// Outside this update: the native calls resize the window through GPUI.
cx.spawn(async move |_, _| tray::reveal(hwnd)).detach();
cx.spawn(async move |_, _| tray::reveal(hwnd, true))
.detach();
}
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
@@ -126,6 +155,35 @@ impl RootView {
}
},
);
// The end of a Match showed its recap: « Paramètres » gives way as for a champ select,
// but the window stays as it is, hidden, minimised or behind League: never in front.
let recap = cx.subscribe_in(&page, window, |this, _, _: &RecapOpened, window, cx| {
if this.screen == Screen::Settings {
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).
let live_match = cx.subscribe_in(
&page,
window,
|this, _, _: &LiveMatchStarted, window, cx| {
if let Some(hwnd) = tray::window_hwnd(window) {
cx.spawn(async move |_, _| tray::reveal(hwnd, false))
.detach();
}
if this.screen == Screen::Settings {
this.show_page(window, cx);
}
},
);
// Saved with the other preferences; a failure keeps the choice for the session.
let sort = cx.subscribe(
&page,
@@ -137,7 +195,12 @@ impl RootView {
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
spawn_follower(
tracker.clone(),
riot_id.clone(),
catalog_refresh.clone(),
tx.clone(),
);
Screen::Page
};
if hidden {
@@ -154,11 +217,15 @@ impl RootView {
focus: initial_focus(window, cx),
screen,
tracker,
catalog_refresh,
fallback_riot_id: riot_id,
tx,
blank: hidden,
_form_events: form_events,
_champ_select: champ_select,
_recap: recap,
_live_match: live_match,
_settings: settings,
_sort: sort,
}
}
@@ -171,7 +238,10 @@ impl RootView {
if self.screen == Screen::Page {
self.screen = Screen::Settings;
// Windows holds the launch at logon: read it as the settings open.
self.form.update(cx, |form, _| form.read_logon_launch());
self.form.update(cx, |form, _| {
form.read_logon_launch();
form.read_accounts();
});
self.page.update(cx, |page, cx| page.hidden(window, cx));
self.focus.focus(window, cx);
cx.notify();
@@ -259,6 +329,8 @@ fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
struct Setup {
tracker: Arc<Tracker>,
/// The cache of the items' and augments' names and icons.
game_data: Option<GameData>,
riot_id: String,
notice: Option<String>,
store: KeyStore,
@@ -296,6 +368,7 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
.with_client(Box::new(LeagueClient::new()));
Ok(Setup {
tracker: Arc::new(tracker),
game_data: Some(GameData::new(dir.join("game-data"))),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
@@ -304,12 +377,16 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
fn main() {
release::handle_command();
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
// The log opens after the single-instance check: a relayed launch must not write to the
// running instance's log, nor rotate it from under it. Flushes when main returns.
let (_instance, starting, _journal) = match single_instance::launch() {
Ok(Some(primary)) => (primary.instance, primary.starting, journal::start()),
Ok(None) => return,
Err(error) => {
let _journal = journal::start();
log::error!("Failed to check for a running instance: {error}");
return;
}
};
// Started by the logon entry: hidden, or minimized (#67).
let at_logon = logon::launched_at_logon();
@@ -317,10 +394,12 @@ fn main() {
let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
let app = gpui_kit::application().with_assets(assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
journal::flush_on_quit(cx);
card_grid::init(cx);
page::init(cx);
theme::init(cx);
#[cfg(feature = "profile")]
profile::start(cx);
+102 -175
View File
@@ -1,25 +1,23 @@
//! The page and its two tabs: the shared state and the navigation. `display` renders the header
//! row and the alerts; `home`, `champ_select` and `statistics` render the content under them.
//! The page and its screens: the shared state. `navigation` switches between them, `display`
//! renders the header row and the alerts; `home`, `champ_select`, `in_game`, `statistics` and
//! `matches` render the content under them.
use crate::banner_art::BannerArt;
use crate::card::Card;
use crate::card_grid::{CardGrid, CardHovered, Paging};
use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::{Deferred, Fade, FadePhase, MatchAnimation, MatchEnd};
use crate::motion::{Deferred, Fade, MatchAnimation, MatchEnd};
use crate::ring::Ring;
use crate::stage::{Entry, Leave, Taken};
use crate::worker::{LiveChampSelect, Msg, RefreshGate};
use arena_tracker_core::{
Account, ChampionSearch, ChampionSort, Format, Scope, SeasonScope, StateFilter, Statistics,
Status, SyncProgress, Tracker,
Account, ChampionSearch, ChampionSort, Format, LiveMatch, Scope, SeasonScope, StateFilter,
Statistics, Status, SyncProgress, Tracker,
};
use gpui_kit::base::Button as BaseButton;
use gpui_kit::base::async_util::Sender;
use gpui_kit::component::input::InputState;
use gpui_kit::component::select::{SelectItem, SelectState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::component::select::{SearchableVec, SelectGroup, SelectItem, SelectState};
use gpui_kit::*;
use profiling::shown;
use scrollbar::PageScrollbar;
@@ -33,18 +31,29 @@ mod cards;
mod champ_select;
mod display;
mod displayed;
mod friends;
mod home;
mod hover;
mod in_game;
mod lifecycle;
mod links;
mod matches;
mod navigation;
mod playback;
mod profiling;
mod ring_hover;
mod scrollbar;
mod setup;
mod statistics;
mod worker_messages;
#[cfg(test)]
mod tests;
pub(crate) mod tests;
/// Binds the keys of the page's own views.
pub(crate) fn init(cx: &mut App) {
matches::init(cx);
}
/// The page's padding on every side: the card grid derives its width from it.
pub(crate) const PAGE_PADDING: f32 = 12.;
@@ -64,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;
@@ -90,6 +104,8 @@ pub struct Launch {
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
/// The preference: the end-of-game block of a Match shows it in « Parties ».
pub open_recap_at_match_end: bool,
}
/// The page entered or left an Arena champ select.
@@ -98,17 +114,56 @@ pub struct ChampSelectTransition {
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The end of a Match opened its recap in « Parties »: « Paramètres » gives way, as for a champ
/// select, but the window is left as it is (#129).
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 {}
/// The two pages the navigation switches between.
/// A Live Match started (#109): « Paramètres » gives way, and a window minimised or hidden
/// opens again without the focus, the game keeping the keyboard.
pub struct LiveMatchStarted;
impl EventEmitter<LiveMatchStarted> for Page {}
/// The screens the page switches between: « Défi » and « Parties » are tabs of the top bar,
/// « Statistiques » the Challenge's detail page, opened from the banner, and « Sélection » and
/// « En partie » the tabs of a phase, there only while an Arena champ select or a Live Match
/// runs.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Tab {
/// « Défi », the home: the Challenge of one Season.
Challenge,
/// « Statistiques »: the analysis by Account, Season and Format.
Statistics,
/// « Parties »: the Matches of the Challenge's Account and the recap of one.
Matches,
/// « Sélection »: the champ select's banner, its Anvil champions and « Autres champions ».
ChampSelect,
/// « En partie »: the champion of the Live Match and what it can bring to the Challenge.
InGame,
}
impl Tab {
/// « Sélection » and « En partie », the tabs of a phase: their banner is about it only.
fn is_phase(self) -> bool {
matches!(self, Tab::ChampSelect | Tab::InGame)
}
/// Whether the screen shows the home's statistics (its Account and Season), not the scope
/// of « Statistiques ».
fn home_scoped(self) -> bool {
match self {
Tab::Challenge | Tab::ChampSelect | Tab::InGame | Tab::Matches => true,
Tab::Statistics => false,
}
}
}
/// A followed Match waiting to play: of several, the strongest plays, and the most recent of the
@@ -120,13 +175,17 @@ struct WaitingMatch {
champion_id: u32,
}
/// The end of a followed Match on « Défi », from the round that stored it to the end of its
/// animation; `Page::end_match` drops it all.
/// The end of a followed Match on « Défi », or on « Parties » when it opened its recap there
/// (#110), from the round that stored it to the end of its animation; `Page::end_match` drops it
/// all.
#[derive(Default)]
struct MatchPlayback {
/// The Match to play once the statistics with it are shown and « Défi » is in front: it
/// waits there whatever hides « Défi » meanwhile.
/// The Match to play once the statistics with it are shown and its screen is in front: it
/// waits there whatever hides the screen meanwhile.
waiting: Deferred<WaitingMatch>,
/// The screen is « Parties », where the end of the Match opened its recap, rather than
/// « Défi ».
on_matches: bool,
/// The statistics shown do not hold the queued Match yet.
stats_pending: bool,
/// The animation running, fixed when it started.
@@ -162,10 +221,18 @@ pub struct Page {
/// As of the last follower round or refresh.
status: Status,
champ_select: LiveChampSelect,
/// The Account of `champ_select`, resolved when its Riot ID changes.
champ_select_account: Option<String>,
/// The Riot ID `champ_select_account` was resolved for.
champ_select_riot_id: Option<String>,
/// The Live Match the client plays (#109): « En partie » is there while it lasts.
live_match: Option<LiveMatch>,
/// The Live Match that became a Match with its end-of-game block: the client stays in its
/// game until its lobby, but its tab does not come back.
match_over: Option<LiveMatch>,
/// What « En partie » shows, prepared when the Live Match or the statistics change.
in_game: in_game::InGame,
/// The Account of the phase (`champ_select`, else `live_match`), resolved when its Riot ID
/// changes.
phase_account: Option<String>,
/// The Riot ID `phase_account` was resolved for.
phase_riot_id: Option<String>,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
@@ -243,13 +310,17 @@ pub struct Page {
/// The Account and scope `home_stats` or `home_error` were computed for: the home does not
/// depend on the Format, so a change of Format keeps them.
home_computed: Option<(String, Scope)>,
/// What the banner shows, prepared when the statistics change.
/// What the home's banner shows, prepared when the statistics change.
banner: home::BannerContent,
/// What the champ select's banner shows, prepared with its cards.
champ_select_banner: home::BannerContent,
champ_select_splashes: HashMap<u32, Rc<arena_tracker_core::Splash>>,
/// The banner's ring: a cached view.
ring: Entity<Ring>,
/// The grid whose card lit the ring's tick.
lit_by: Option<EntityId>,
/// The champion the pointer aims at on the ring.
ring_hover: ring_hover::RingHover,
/// The banner's illustration, its own: given back while the banner is not shown.
banner_art: Entity<BannerArt>,
/// The home's own filter and search: never persisted, « Tous » at each launch.
@@ -267,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>,
@@ -300,162 +374,15 @@ pub struct Page {
champ_select_scrollbar: Entity<PageScrollbar>,
/// The section's header button, which the keyboard reaches.
others_focus: FocusHandle,
/// « Parties »: its list, its recap and the jobs that read them.
matches: matches::Matches,
/// The preference: the end-of-game block of a Match opens its recap in « Parties ».
open_recap_at_match_end: bool,
/// The latest game whose end chose the screen shown: it is decided once (#129).
decided_game: Option<u64>,
/// Lights the ring's tick of the card hovered in « Autres champions », lifts it, and scrolls the
/// champ select to the card the keyboard reaches; its grid is made again at each fold.
others_hover: [Subscription; 3],
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
impl Page {
/// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them.
fn navigation(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (ring, muted, active, active_foreground, hover, hover_foreground) = (
theme.ring,
theme.tab_foreground,
theme.tab_active,
theme.tab_active_foreground,
theme.accent,
theme.accent_foreground,
);
let tabs = [
("tab-challenge", "Défi", Tab::Challenge),
("tab-statistics", "Statistiques", Tab::Statistics),
];
div()
.h_flex()
.gap_1()
.flex_shrink_0()
.children(tabs.map(|(id, label, tab)| {
let current = self.tab == tab;
// The champ select takes the window: « Statistiques » waits for its end.
let disabled = tab == Tab::Statistics && self.in_champ_select();
BaseButton::new(id)
.disabled(disabled)
.px_3()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
// Always bordered, so the focus ring does not shift the label.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| {
style.border_color(if current { active_foreground } else { ring })
})
.text_color(if current { active_foreground } else { muted })
.when(current, |button| button.bg(active))
.when(!current && !disabled, |button| {
button.hover(|style| style.bg(hover).text_color(hover_foreground))
})
.when(disabled, |button| button.opacity(0.5))
.accessibility_label(label)
.debug_selector(|| id.into())
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}))
}
fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
// The champ select takes the window: the Statistics tab waits for its end.
if tab == Tab::Statistics && self.in_champ_select() {
return;
}
if self.tab != tab {
self.tab = tab;
// The grids leave under the veil: no card stays lifted over it.
self.lifts.clear();
if cx.reduce_motion() || !window.is_visible() {
// Nothing to see: the end state at once.
self.end_fade(window, cx);
} else {
// From where the veil is: a switch during a transition does not wait for it.
let now = cx.background_executor().now();
let veil = self.veil(cx);
self.fade = Some(if self.shown_tab == tab {
Fade::uncovering(veil, now)
} else {
Fade::covering(veil, now)
});
self.next_fade_frame(window, cx);
}
cx.notify();
}
}
/// Draws the screen of the tab chosen.
fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.shown_tab == self.tab {
return;
}
self.shown_tab = self.tab;
// The home grid is no longer under the pointer.
self.release_home(cx);
// The screen arriving was not kept up to date while hidden, and is prepared only now: a
// switch undone under the veil prepares nothing.
self.refresh_table(cx);
if self.home_cards_stale {
self.prepare_home_cards(cx);
}
self.refresh_home(cx);
if self.shown_tab == Tab::Statistics {
// The home grid is not shown: its portraits are given back, and come back with the
// grid.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
// Nor is the banner: its illustration too.
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
} else {
// Nor is the table: its portraits.
self.table
.update(cx, |table, cx| table.release_images(window, cx));
}
}
/// Shows the end of the transition, if one runs, at once.
fn end_fade(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.fade = None;
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.show_tab(window, cx);
self.play_waiting(window, cx);
cx.notify();
}
/// Asks for the transition's next frame, once.
fn next_fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.frame_asked {
self.frame_asked = true;
cx.on_next_frame(window, |page, window, cx| page.fade_frame(window, cx));
}
}
/// One frame of the transition: the screen arriving replaces the one leaving under the full
/// veil, and no frame is asked for once the veil is lifted.
fn fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.frame_asked = false;
let Some(fade) = &self.fade else {
return;
};
let now = cx.background_executor().now();
if fade.finished(now) {
match fade.phase() {
FadePhase::Out => {
self.show_tab(window, cx);
// The champ select that ended leaves under the full veil: the home comes
// out of it, as after a switch of tabs.
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.fade = Some(Fade::uncovering(1., now));
}
FadePhase::In => return self.end_fade(window, cx),
}
}
self.next_fade_frame(window, cx);
cx.notify();
}
}
+5 -6
View File
@@ -6,8 +6,8 @@ use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// Computes the cards' order again: for when the home statistics (the champ select's during
/// a champ select) or the sort change, and for nothing else.
/// Computes the cards' order again: for when the home statistics (the champ select's Challenge
/// during a champ select) or the sort change, and for nothing else.
pub(in crate::page) fn reorder(&mut self) {
self.order = self.sorted_order();
}
@@ -73,10 +73,9 @@ impl Page {
self.reorder();
if self.in_champ_select() {
self.prepare_champ_select(cx);
} else {
self.prepare_home_cards(cx);
self.refresh_home(cx);
}
self.prepare_home_cards(cx);
self.refresh_home(cx);
cx.emit(ChampionSortChosen(sort));
cx.notify();
}
@@ -123,7 +122,7 @@ impl Page {
/// Recomputes which cards the home shows from its own filter and search, with the total
/// untouched; while the home is not shown, the next switch does.
pub(in crate::page) fn refresh_home(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Challenge || self.in_champ_select() {
if self.shown_tab != Tab::Challenge {
return;
}
if self.hold_grid {
+52 -26
View File
@@ -11,19 +11,39 @@ mod motion;
mod render;
impl Page {
/// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the
/// Accounts do), so preparing statistics builds no Riot ID per Account every time.
pub(in crate::page) fn champ_select_account(&mut self) -> Option<String> {
let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?;
if self.champ_select_riot_id.as_deref() != Some(id) {
self.champ_select_riot_id = Some(id.into());
self.champ_select_account = self
/// The Account of the phase: the live champ select's, else the Live Match's. Resolved when
/// the signed-in Riot ID changes (or the Accounts do), so preparing statistics builds no
/// Riot ID per Account every time.
pub(in crate::page) fn phase_account(&mut self) -> Option<String> {
let id = (self.champ_select.as_ref().map(|(id, _)| id.as_str()))
.or(self.live_match.as_ref().map(|live| live.riot_id.as_str()))?;
if self.phase_riot_id.as_deref() != Some(id) {
self.phase_riot_id = Some(id.into());
self.phase_account = self
.accounts
.iter()
.find(|a| same_riot_id(&account_riot_id(a), id))
.map(|a| a.puuid.clone());
}
self.champ_select_account.clone()
self.phase_account.clone()
}
/// The phase's Account and the current Season stand in for the home's, or the home's come
/// back: what was computed for the scope left goes while the new one loads.
pub(in crate::page) fn rescope(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
self.phase_riot_id = None;
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.reorder();
self.reload_in_background(window, cx);
// Nor does the banner keep the previous scope's Challenge while the new one loads: its
// Season, its ticks and its splash go with the statistics.
self.prepare_banner(cx);
}
/// The champ select the client reports changed: entered, left, another one, or the same
@@ -38,18 +58,21 @@ impl Page {
let next = champ_select.as_ref();
let changed_page = previous.is_some() != next.is_some();
let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id);
// The game it launched is the same Account's in the same Season: its statistics stay.
let launched = next.is_none()
&& (previous.zip(self.live_match.as_ref()))
.is_some_and(|((id, _), live)| same_riot_id(id, &live.riot_id));
self.champ_select = champ_select;
if changed_page {
if self.in_champ_select() {
// The champ select is about the Challenge, whatever tab was open.
self.tab = Tab::Challenge;
// Nothing plays during a champ select: what waited is no longer news.
self.stop_holding();
self.end_match(cx);
// The phase decides: « Sélection » shows, whatever screen was open, at once (its
// entry's band of light is the transition).
self.tab = Tab::ChampSelect;
self.lifts.clear();
self.end_fade(window, cx);
// The home grid gives way to the champ select's sections.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
// Its entry plays once the window shows it (#63 reveals it without focus).
self.entry_waiting = true;
} else {
@@ -59,26 +82,29 @@ impl Page {
.update(cx, |grid, cx| grid.release_images(window, cx));
// An animation asked for during the champ select plays on the home.
self.playback.stats_pending = self.playback.active();
// The phase decides: « Sélection » goes, and « Défi » shows, from wherever the
// player was (under the veil the hand left for, when it left); « En partie »
// when the champ select launched the game.
let next = if self.in_live_match() {
Tab::InGame
} else {
Tab::Challenge
};
self.set_tab(next, window, cx);
}
}
if switch {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
self.champ_select_riot_id = None;
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.reorder();
// A new champ select starts with « Autres champions » folded and searchless, at the
// top of the page.
self.fold_others(window, cx);
self.paging.scroll.set_offset(point(px(0.), px(0.)));
self.reload_in_background(window, cx);
// Nor does the banner keep the previous scope's Challenge while the new one
// loads: its Season, its ticks and its splash go with the statistics.
self.prepare_banner(cx);
if launched {
// Only the banner stops being the champ select's.
self.prepare_banner(cx);
} else {
// The phase shows the active Account, and so does the page after it.
self.show_account(None, window, cx);
}
}
if changed_page {
cx.emit(ChampSelectTransition {
+3 -4
View File
@@ -71,23 +71,22 @@ impl Page {
.map_or(&[][..], |s| s.rows.as_slice());
let cards =
self.champ_select_cards(rows.iter().filter(|row| ids.contains(&row.champion.id)));
// A list the client did not send dims no tick: the ring would look empty.
self.ring.update(cx, |ring, cx| ring.set_anvil(anvil, cx));
if champ_select.is_some() {
let remaining_pickable = cards.iter().filter(|card| !card.greyed());
let first = remaining_pickable.clone().next().or_else(|| cards.first());
let splash = first
.and_then(|card| self.champ_select_splashes.get(&card.id))
.cloned();
self.banner = home::BannerContent::champ_select(
self.champ_select_banner = home::BannerContent::champ_select(
self.home_season.as_ref(),
self.home_statistics(),
anvil.is_some(),
remaining_pickable.count(),
splash,
);
self.select_art(self.ring.read(cx).lit(), cx);
}
// A list the client did not send dims no tick: the ring would look empty.
self.dress_banner(cx);
self.anvil_count = cards.len().to_string().into();
let shown = (0..cards.len()).collect();
// The hand's cards are dealt once they come: the statistics load at each entry.
+12 -4
View File
@@ -1,13 +1,19 @@
use crate::card::{Card, Reason};
use crate::card_grid::CardGrid;
use crate::motion::Fade;
use crate::page::Page;
use crate::page::{Page, Tab};
use crate::stage::{self, BEFORE_VEIL, Entry, HandAt, HandMotion, Leave, Taken};
use gpui_kit::*;
use std::rc::Rc;
use std::time::Instant;
impl Page {
/// Whether « Sélection » is the screen drawn and chosen: the champ select's motion plays
/// there only.
pub(in crate::page) fn selection_shown(&self) -> bool {
self.tab == Tab::ChampSelect && self.shown_tab == Tab::ChampSelect
}
/// Whether the page is in front of the player and may animate: the window shown, not
/// behind « Paramètres », and the Windows « Show animations » setting on.
pub(in crate::page) fn may_animate(&self, window: &Window, cx: &App) -> bool {
@@ -18,7 +24,7 @@ impl Page {
/// light, the title, then the hand dealt once it has its cards. With the Windows setting off
/// the hand is simply there.
pub(in crate::page) fn start_entry(&mut self, window: &Window, cx: &mut Context<Self>) {
if !self.entry_waiting || !self.in_champ_select() {
if !self.entry_waiting || !self.in_champ_select() || !self.selection_shown() {
return;
}
if cx.reduce_motion() {
@@ -71,13 +77,15 @@ impl Page {
let grid = self.anvil_grid.read(cx);
let cards = grid.cards().len();
let leave = Leave::new(grid.cards(), hand_at, now);
// A veil already on its way (the player chose « Défi ») stays where it is meanwhile.
let veil = self.veil(cx);
self.forget_stage();
// No card stays lifted over the hand leaving.
self.lifts.clear();
self.lifted_by_keyboard = None;
self.leave = Some(leave);
let veil_from = if cards == 0 { now } else { now + BEFORE_VEIL };
self.fade = Some(Fade::covering(0., veil_from));
self.fade = Some(Fade::covering(veil, veil_from));
self.next_fade_frame(window, cx);
cx.notify();
}
@@ -97,7 +105,7 @@ impl Page {
window: &Window,
cx: &mut Context<Self>,
) {
if !self.may_animate(window, cx) {
if !self.selection_shown() || !self.may_animate(window, cx) {
return;
}
let now = cx.background_executor().now();
+46 -4
View File
@@ -1,7 +1,10 @@
use super::UNKNOWN_ANVIL;
use crate::card_grid::MAX_WIDTH;
use crate::input_frame::input_frame;
use crate::page::{
Page,
home::{StatsNotice, count_badge, notice_line},
shown,
};
use crate::theme::heading;
use gpui_kit::base::Button as BaseButton;
@@ -12,6 +15,43 @@ use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
impl Page {
/// « Sélection »: the champ select's banner, its Anvil champions and « Autres champions ».
/// The column is taller than the window, and scrolls then, « Autres champions » with it (its
/// grid builds only the rows in view).
pub(in crate::page) fn champ_select_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let mut column = self.banner_column(window, cx);
if shown("anvil") {
column = column.child(self.anvil_area(window.viewport_size().width, cx));
}
// With the statistics missing there is nothing to browse: the notice stands alone.
if shown("others") && self.stats_notice().is_none() {
column = column.child(self.others_area(window.viewport_size().width, cx));
}
// One scrolling for all of it, with its scrollbar in the lane the sections leave.
vec![
div()
.relative()
.flex_1()
.min_h_0()
.w_full()
.max_w(px(MAX_WIDTH))
.mx_auto()
.child(
column
.id("champ-select")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.paging.scroll),
)
.child(self.champ_select_scrollbar.clone())
.into_any_element(),
]
}
/// What stands in place of the Anvil champions row, if anything: the statistics are missing,
/// or the client gave no list (which does not make any champion without an anvil), or an
/// empty one.
@@ -152,10 +192,12 @@ impl Page {
.gap_x_3()
.gap_y_2()
.child(
Input::new(&self.others_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.others_search_input,
Input::new(&self.others_search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.)),
)
.child(self.sort_selector(cx)),
)
+21 -12
View File
@@ -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",
@@ -67,22 +70,21 @@ impl Render for Page {
// A card lifting or settling asks for the next frame, and none once they are still.
let now = cx.background_executor().now();
if let Some(animation) = self.playback.animation {
if animation.finished(now) || cx.reduce_motion() || !self.challenge_visible(window) {
if animation.finished(now) || cx.reduce_motion() || !self.playback_visible(window) {
self.end_match(cx);
} else {
// The comet lands: the splash of the champion just validé settles in, when it is
// the banner's, the last champion validé. A validation older than the banner's
// (its Match arrived late) leaves the banner as a reload shows it.
// The comet lands: the splash of the champion just validé settles in, when its
// Match is the banner's (the last Match on « Défi », the one chosen on
// « Parties »). A Match older than that (it arrived late) leaves the banner as a
// reload shows it.
if animation.has_comet()
&& animation.since_landing(now) >= 0.
&& self.playback.previous_banner.take().is_some()
{
let last_validated = (self.home_statistics())
.and_then(|s| s.challenge.as_ref())
.and_then(|c| c.completion_order.last().copied());
let splash = self.banner.splash.clone();
let splash = self.banner_splash();
let own = self.banner_champion() == Some(animation.champion_id);
self.banner_art.update(cx, |art, cx| {
if last_validated == Some(animation.champion_id) {
if own {
art.reveal(splash, cx);
} else {
art.set_target(splash, cx);
@@ -104,7 +106,10 @@ 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 = (!busy)
.then(|| self.friend_status())
.flatten()
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into());
div()
// The pointer takes over from the keyboard: the card it lifted goes down.
@@ -140,8 +145,8 @@ impl Render for Page {
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The champ select is about the signed-in Account.
.disabled(self.in_champ_select())
// The phases are about the signed-in Account.
.disabled(self.in_phase())
.w(px(260.))
.min_w(px(150.)),
)
@@ -164,6 +169,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()))
})
@@ -179,6 +185,9 @@ impl Render for Page {
.children(match self.shown_tab {
Tab::Challenge => self.home_content(window, cx),
Tab::Statistics => self.statistics_content(cx),
Tab::Matches => self.matches_content(window, cx),
Tab::ChampSelect => self.champ_select_content(window, cx),
Tab::InGame => self.in_game_content(window, cx),
})
.when(self.fade.is_some(), |screen| {
let veil = cx.theme().background.opacity(self.veil(cx));
+74 -22
View File
@@ -1,11 +1,21 @@
//! What the page displays: the Account, whether its data is stale, the official count, the
//! error to show and the scope its statistics are computed for.
use crate::page::{Page, Tab};
use arena_tracker_core::{Account, ProgressCheck, Scope, SeasonScope};
use crate::page::Page;
use arena_tracker_core::{Account, ProgressCheck, Scope, SeasonScope, StateFilter};
use gpui_kit::*;
impl Page {
/// The Account shown: the pinned one, else the one being updated.
/// « Paramètres » deleted an Account: the Accounts are read again, and the active Account
/// shows if the deleted one was pinned. The status is read again too: it may name the
/// deleted Account as the last active one.
pub fn account_deleted(&mut self, puuid: &str, window: &mut Window, cx: &mut Context<Self>) {
self.status = self.tracker.status();
let pinned = self.pinned.clone().filter(|pinned| pinned != puuid);
self.show_account(pinned, window, cx);
}
/// The Account shown: the pinned one, else the active one.
pub(in crate::page) fn viewed(&self) -> Option<&Account> {
self.pinned
.as_ref()
@@ -15,11 +25,58 @@ impl Page {
.or(self.accounts.first())
}
/// The Account whose data the page shows: during a champ select the one signed in to the
/// client, whatever the pinned or followed one is, else `viewed`.
/// The active Account: the one signed in to the client, else the last one known while it is
/// closed. The top bar lists it first, and a phase, a Match's end and the start show it.
pub(in crate::page) fn active_account(&self) -> Option<&Account> {
(self.status.updating.as_ref())
.or(self.last_active.as_ref())
.or(self.accounts.first())
}
/// The Account chosen in the top bar, when it is not the active one: the home's banner says
/// whose Challenge it shows, and nothing is official or plays for it.
fn other_account(&self) -> Option<&Account> {
let active = self.active_account()?;
self.viewed().filter(|viewed| viewed.puuid != active.puuid)
}
/// Starts the banner's overline with « Défi de Pseudo · » for an Account that is not the
/// active one.
pub(in crate::page) fn name_other_account(&mut self) {
let Some(name) = self.other_account().map(|a| a.game_name.clone()) else {
return;
};
let season = &self.banner.season;
self.banner.season = if season.is_empty() {
format!("Défi de {name}")
} else {
format!("Défi de {name} · {season}")
}
.into();
}
/// Shows `pinned` (none: the active Account) on « Défi », « Statistiques » and « Parties ».
/// Another Account starts with « Tous » in both filters, sort and theme staying; its
/// statistics are computed once, on the worker (`rescope`).
pub(in crate::page) fn show_account(
&mut self,
pinned: Option<String>,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.pinned != pinned {
self.pinned = pinned;
self.filter = StateFilter::All;
self.home_filter = StateFilter::All;
}
self.rescope(window, cx);
}
/// The Account whose data the page shows: during a champ select or a Live Match the one
/// signed in to the client, whatever the pinned or followed one is, else `viewed`.
pub(in crate::page) fn displayed(&self) -> Option<&Account> {
if self.in_champ_select() {
let puuid = self.champ_select_account.as_deref()?;
if self.in_phase() {
let puuid = self.phase_account.as_deref()?;
return self.accounts.iter().find(|a| a.puuid == puuid);
}
self.viewed()
@@ -41,10 +98,10 @@ impl Page {
/// whether the page shows it as the home's Challenge or as the selected Season.
pub(in crate::page) fn official(&self) -> Option<&ProgressCheck> {
let updated = matches!((self.displayed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid);
let shown = match (self.shown_tab, &self.season) {
(Tab::Challenge, _) => self.home_season.as_deref(),
(Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()),
(Tab::Statistics, SeasonScope::AllSeasons) => None,
let shown = match &self.season {
_ if self.shown_tab.home_scoped() => self.home_season.as_deref(),
SeasonScope::Season(season) => Some(season.as_str()),
SeasonScope::AllSeasons => None,
};
let current = shown.is_some() && shown == self.current_season.as_deref();
(updated && current).then_some(&self.status.official_progress)
@@ -52,21 +109,16 @@ impl Page {
/// The tab's own statistics error: the home may have computed its own.
pub(in crate::page) fn error(&self) -> Option<&String> {
match (self.shown_tab, &self.home_scope) {
(Tab::Challenge, Some(_)) => self.home_error.as_ref(),
_ => self.stats_error.as_ref(),
if self.shown_tab.home_scoped() && self.home_scope.is_some() {
self.home_error.as_ref()
} else {
self.stats_error.as_ref()
}
}
/// The Statistics tab's scope, during a champ select too: only the home's Challenge is the
/// champ select's (`prepare_statistics`).
pub(in crate::page) fn statistics_scope(&self) -> Scope {
if self.in_champ_select()
&& let Some(season) = &self.current_season
{
return Scope {
season: SeasonScope::Season(season.clone()),
format: None,
};
}
Scope {
season: self.season.clone(),
format: self.format,
+341
View File
@@ -0,0 +1,341 @@
//! 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::input_frame::input_frame;
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.
const ADD_FRIEND: &str = "+";
/// What the Friends need from the page.
pub(super) struct Friends {
/// The field that takes a Riot ID.
input: Entity<InputState>,
open: bool,
/// The Riot ID is being looked up: Enter does nothing meanwhile.
pending: bool,
/// Why the last Riot ID was refused, and whether « Paramètres » is the way out.
refusal: Option<(String, bool)>,
/// The puuids of the Friends, as of the last read of the Accounts.
pub(super) ids: HashSet<String>,
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)]
struct Import {
running: Option<String>,
/// Asked for while another ran: the latest Friend asked for wins.
queued: Option<String>,
line: Option<SharedString>,
/// The Friend whose last import failed, and why.
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 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;
let added = matches!(result, Ok(AddedFriend::Added(_)));
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);
if added {
self.set_tab(super::Tab::Challenge, 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.line = self
.accounts
.iter()
.find(|a| a.puuid == puuid)
.map(|a| friend_sync_line(&a.game_name, None).into());
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.line = self
.accounts
.iter()
.find(|a| a.puuid == puuid)
.map(|a| friend_sync_line(&a.game_name, Some(progress)).into());
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.line = 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<SharedString> {
self.friends.import.line.clone()
}
/// 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(
input_frame(
&self.friends.input,
gpui_kit::component::input::Input::new(&self.friends.input),
)
.w(px(260.)),
)
.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(),
)
}
}
#[cfg(test)]
mod tests;
+340
View File
@@ -0,0 +1,340 @@
//! 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 crate::page::friends::ADD_FRIEND;
use crate::page::tests::friends_fixtures::{CARL, Handles, tracker};
use crate::page::tests::page_fixtures::{draw, open_page_with_tracker};
use crate::page::{Page, Tab};
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().map(|s| s.to_string()))
}
/// 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;
crate::page::tests::page_fixtures::switch_tab(&page, &mut window, Tab::Matches);
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.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
})
.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_eq!(p.tab, Tab::Challenge);
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.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
})
.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());
assert_eq!(tracker.match_count("Carl").unwrap(), 0);
});
}
#[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)]);
});
}
+33 -45
View File
@@ -10,11 +10,15 @@ use gpui_kit::*;
mod banner;
mod content;
mod data;
mod dress;
#[cfg(test)]
pub(in crate::page) use content::IDENTIFYING;
pub(in crate::page) use content::{BannerContent, Line};
use super::{Page, shown};
use crate::card_grid::MAX_WIDTH;
use crate::input_frame::input_frame;
use crate::theme::heading;
/// The filters on offer, whatever the Season.
@@ -115,9 +119,9 @@ impl Page {
if self.home_season.is_none() {
return Some(StatsNotice::NoSeason);
}
// During a champ select the Account is the one signed in to the client, known by the
// follower's status; else it is the one viewed.
let no_account = if self.in_champ_select() {
// During a champ select or a Live Match the Account is the one signed in to the client,
// known by the follower's status; else it is the one viewed.
let no_account = if self.in_phase() {
self.status.updating.is_none()
} else {
self.viewed().is_none()
@@ -129,15 +133,14 @@ impl Page {
})
}
/// Under the status messages: the banner, then the heading with the filters and
/// search, and the cards. It holds no chart (#71): the cached charts row only belongs to the
/// Statistics tab. Everything is one centred column, as wide as the mockup's.
pub(in crate::page) fn home_content(
/// The centred column of « Défi », « Sélection » and « En partie », as wide as the mockup's,
/// with the banner on top.
pub(in crate::page) fn banner_column(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let mut column = div()
) -> Div {
let column = div()
.v_flex()
.flex_1()
.min_h_0()
@@ -146,39 +149,21 @@ impl Page {
.mx_auto()
.gap_3();
if shown("banner") {
column = column.child(self.banner(window, cx));
}
if self.in_champ_select() {
// The champ select takes the place of the grid, its filters and its search: the
// column is taller than the window, and scrolls then, « Autres champions » with it
// (its grid builds only the rows in view).
if shown("anvil") {
column = column.child(self.anvil_area(window.viewport_size().width, cx));
}
// With the statistics missing there is nothing to browse: the notice stands alone.
if shown("others") && self.stats_notice().is_none() {
column = column.child(self.others_area(window.viewport_size().width, cx));
}
// One scrolling for all of it, with its scrollbar in the lane the sections leave.
return vec![
div()
.relative()
.flex_1()
.min_h_0()
.w_full()
.max_w(px(MAX_WIDTH))
.mx_auto()
.child(
column
.id("champ-select")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.paging.scroll),
)
.child(self.champ_select_scrollbar.clone())
.into_any_element(),
];
column.child(self.banner(window, cx))
} else {
column
}
}
/// Under the status messages: the banner, then the heading with the filters and
/// search, and the cards. It holds no chart (#71): the cached charts row only belongs to the
/// Statistics tab.
pub(in crate::page) fn home_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let mut column = self.banner_column(window, cx);
if self.home_season.is_some() {
match self.stats_notice() {
None => {
@@ -262,10 +247,13 @@ impl Page {
.items_center()
.gap_3()
.child(
Input::new(&self.home_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.home_search_input,
Input::new(&self.home_search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.))
.debug_selector(|| "home-search".into()),
)
.child(
TabBar::new("home-filter")
+88 -86
View File
@@ -1,38 +1,48 @@
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::assets::IconName;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{BannerContent, Line, NO_SEASON, Page};
use super::{Line, NO_SEASON, Page};
use crate::banner_art::BannerArt;
use crate::motion::{COUNTER_ROLL, ease_out};
use crate::ring::{self, Tick};
use crate::page::Tab;
use crate::theme::{banner_band, gold_ink, heading};
use std::rc::Rc;
impl Page {
/// The banner, on the home and during a champ select: the ring, then the Season, the
/// Challenge's count and its two lines, over the splash of the last champion Completed. In a
/// The banner, on the home, on « Parties » and during a champ select: the ring, then the
/// Season, the Challenge's count and its two lines, over the splash of the champion of the
/// last Match (of the Match chosen, on « Parties »). In a
/// narrow window the ring goes above the text, and the splash covers the whole banner under a
/// stronger fade.
pub(super) fn banner(&self, window: &mut Window, cx: &mut Context<Page>) -> impl IntoElement {
pub(in crate::page) fn banner(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> impl IntoElement {
let layout = BannerLayout::of(window.viewport_size().width);
let now = cx.background_executor().now();
let animation = self.playback.animation;
// Seconds since the comet landed, or since the start without one.
let landed = animation.map(|a| a.since_landing(now));
// The banner says what it said before the Match until the comet lands.
// The banner says what it said before the Match until the comet lands, also while the
// end of the Match waits on « Parties ».
let waiting_here = self.playback.on_matches && self.shown_tab == Tab::Matches;
let text = self
.playback
.previous_banner
.as_ref()
.filter(|_| landed.is_some_and(|t| t < 0.))
.unwrap_or(&self.banner);
.filter(|_| landed.map_or(waiting_here, |t| t < 0.))
.unwrap_or(self.shown_banner());
// The count of champions validés rolls in once the comet lands: 0 to 1.
let roll = animation
.filter(|a| a.has_comet())
.and(landed)
.filter(|t| (0. ..COUNTER_ROLL).contains(t))
.map(|t| t / COUNTER_ROLL);
let aimed = self.ring_hover.aimed.as_ref();
let theme = cx.theme();
let (band, muted, foreground, ink) = (
banner_band(theme),
@@ -50,25 +60,31 @@ impl Page {
},
)])
};
let season_line = (!text.season.is_empty()).then(|| {
div()
.text_xs()
.font_weight(FontWeight::SEMIBOLD)
.text_color(ink)
.debug_selector(|| "banner-season".into())
.child(text.season.clone())
});
let no_season_line = self.home_season.is_none().then(|| {
div()
.text_sm()
.text_color(muted)
.debug_selector(|| "no-season".into())
.child(NO_SEASON)
});
let copy = div()
.v_flex()
.min_w_0()
.when(!layout.narrow, |copy| copy.max_w(relative(0.46)))
.children((!text.season.is_empty()).then(|| {
div()
.text_xs()
.font_weight(FontWeight::SEMIBOLD)
.text_color(ink)
.child(text.season.clone())
}))
.children(self.home_season.is_none().then(|| {
div()
.text_sm()
.text_color(muted)
.debug_selector(|| "no-season".into())
.child(NO_SEASON)
.into_any_element()
}))
// Full width in a narrow window: its last lines keep clear of the corner icon.
.when(layout.narrow && !self.shown_tab.is_phase(), |copy| {
copy.pr(px(40.))
})
.children(season_line)
.children(no_season_line)
.children((!text.title.text.is_empty()).then(|| {
div()
.v_flex()
@@ -99,9 +115,17 @@ impl Page {
.child(title)
.children(rolling)
})
.child(div().text_sm().text_color(muted).child(name(&text.detail)))
// The champion aimed at on the ring takes the first line's place, and the
// second one is only hidden, so that nothing moves.
.child(
div()
.text_sm()
.text_color(muted)
.child(name(aimed.map_or(&text.detail, |aimed| &aimed.line))),
)
.children(text.last_match.as_ref().map(|line| {
div()
.when(aimed.is_some(), |line| line.invisible())
// The new line fades in once the comet lands; the old one stays.
.opacity(
(landed.filter(|t| *t >= 0.))
@@ -131,28 +155,50 @@ impl Page {
})
.gap(px(layout.gap))
.px(px(layout.padding))
.py(px(24.))
.py(px(BANNER_PADDING_Y))
.debug_selector(|| "banner".into())
.child(self.banner_art.clone())
.child(
// Cached: only a change of its ticks or of the lit one draws it again.
div()
.relative()
.size(px(layout.ring))
.flex_none()
.child(
self.ring
.clone()
.cached(StyleRefinement::default().size_full()),
)
.children(
animation.map(|a| self.ring.read(cx).match_layer(a, a.elapsed(now), cx)),
),
)
// Cached: only a change of its ticks or of the lit one draws the ring again.
.child(self.ring_slot(layout.ring, now, cx))
.child(copy)
// A phase's banner is about the phase only.
.children((!self.shown_tab.is_phase()).then(|| self.statistics_button(ink, layout, cx)))
}
/// « Statistiques », a chart icon in the banner's bottom-right corner, over the
/// illustration. Absolute, so it moves neither the text nor the ring and keeps the banner's
/// height. A real button: Tab reaches it, Enter or Space opens the page.
fn statistics_button(
&self,
ink: Hsla,
layout: BannerLayout,
cx: &mut Context<Page>,
) -> impl IntoElement {
const LABEL: &str = "Statistiques";
let theme = cx.theme();
let (ring, hover, hover_foreground) = (theme.ring, theme.accent, theme.accent_foreground);
BaseButton::new("statistics-link")
.absolute()
.right(px(layout.padding))
.bottom(px(BANNER_PADDING_Y))
.p_1()
.rounded_md()
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.text_color(ink)
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label(LABEL)
.tooltip(|window, cx| Tooltip::new(LABEL).build(window, cx))
.debug_selector(|| "statistics-link".into())
.child(Icon::new(IconName::ChartLine))
.on_click(cx.listener(|this, _, window, cx| this.set_tab(Tab::Statistics, window, cx)))
}
}
/// The banner's vertical padding.
const BANNER_PADDING_Y: f32 = 24.;
/// The banner's rounded corners.
const RADIUS: f32 = 16.;
@@ -356,47 +402,3 @@ impl Render for BannerArt {
}
}
}
impl Page {
/// The banner's text and the ring's ticks, for when the home statistics change. Neither
/// follows the Format, the filter, the search nor the sort.
pub(in crate::page) fn prepare_banner(&mut self, cx: &mut Context<Self>) {
let stats = self.home_statistics();
let champ_select = self.in_champ_select();
let splashes = stats
.filter(|_| champ_select)
.into_iter()
.flat_map(|s| &s.rows)
.filter_map(|row| Some((row.champion.id, Rc::new(row.splash.clone()?))))
.collect();
let ticks: Rc<[Tick]> = stats
.and_then(|s| {
Some(ring::ticks(
&s.rows,
&s.challenge.as_ref()?.completion_order,
))
})
.unwrap_or_default()
.into();
if !champ_select {
self.banner = BannerContent::new(self.home_season.as_ref(), stats);
if !self.playback.active() {
self.banner_art
.update(cx, |art, cx| art.set_target(self.banner.splash.clone(), cx));
}
}
self.champ_select_splashes = splashes;
self.ring.update(cx, |ring, cx| ring.set_ticks(ticks, cx));
}
}
impl Page {
pub(in crate::page) fn select_art(&self, hovered: Option<u32>, cx: &mut Context<Self>) {
let splash = match hovered {
Some(id) => self.champ_select_splashes.get(&id),
None => self.banner.splash.as_ref(),
};
self.banner_art
.update(cx, |art, cx| art.set_target(splash.cloned(), cx));
}
}
+69 -17
View File
@@ -1,7 +1,7 @@
use std::ops::Range;
use std::rc::Rc;
use arena_tracker_core::{MatchOutcome, Splash, Statistics};
use arena_tracker_core::{ChampionRow, MatchOutcome, Splash, Statistics};
use gpui_kit::SharedString;
use crate::page::champ_select::UNKNOWN_ANVIL;
@@ -16,7 +16,7 @@ pub(in crate::page) struct Line {
impl Line {
/// `before`, then `bold`, then `after`.
fn new(before: &str, bold: &str, after: &str) -> Line {
pub(in crate::page) fn new(before: &str, bold: &str, after: &str) -> Line {
Line {
text: format!("{before}{bold}{after}").into(),
bold: before.len()..before.len() + bold.len(),
@@ -59,11 +59,72 @@ pub(in crate::page) struct BannerContent {
pub(in crate::page) detail: Line,
/// « Dernière Partie : … », from the stored Matches; none without a Match in the Season.
pub(in crate::page) last_match: Option<Line>,
/// The illustration when no card is hovered.
/// The illustration when no card is hovered: the splash of the last Match's champion, as at
/// home; none without a Match.
pub(in crate::page) splash: Option<Rc<Splash>>,
}
/// The overline of a phase's banner: the Season, then the Challenge's count.
fn overline_with_count(season: Option<&SharedString>, stats: Option<&Statistics>) -> String {
let mut season = season.map(overline).unwrap_or_default();
if let Some(challenge) = stats.and_then(|s| s.challenge.as_ref()) {
use std::fmt::Write;
if !season.is_empty() {
season.push_str(" · ");
}
write!(
season,
"{} / {} validés",
challenge.completed, challenge.total
)
.unwrap();
}
season
}
/// The title of « En partie » while the client has not said the champion played.
pub(in crate::page) const IDENTIFYING: &str = "Champion en cours d’identification";
impl BannerContent {
/// « En partie »'s banner (#109): the Season and the count, the champion played (`row`,
/// once `identified` and its statistics known), and what the Match can bring it: « Un top 1
/// validerait X : 88 / 172 », or the day it was validated. Its splash, none while the
/// champion is not known.
pub(in crate::page) fn in_game(
season: Option<&SharedString>,
stats: Option<&Statistics>,
identified: bool,
row: Option<&ChampionRow>,
) -> Self {
let challenge = stats.and_then(|s| s.challenge.as_ref());
let title = match row {
Some(row) => Line::plain(&row.champion.name),
None if identified => Line::plain("Partie en cours"),
None => Line::plain(IDENTIFYING),
};
let detail = match (row, challenge) {
(Some(row), Some(challenge)) => {
let name = &row.champion.name;
match row.challenge.and_then(|c| c.completed_on) {
Some(day) => Line::new("", name, &format!(" validé le {}", short_date(day))),
None => Line::new(
"Un top 1 validerait ",
name,
&format!(" : {} / {}", challenge.completed + 1, challenge.total),
),
}
}
_ => Line::default(),
};
Self {
season: overline_with_count(season, stats).into(),
title,
detail,
last_match: None,
splash: row.and_then(|row| row.splash.clone()).map(Rc::new),
}
}
pub(in crate::page) fn champ_select(
season: Option<&SharedString>,
stats: Option<&Statistics>,
@@ -71,19 +132,7 @@ impl BannerContent {
count: usize,
splash: Option<Rc<Splash>>,
) -> Self {
let mut season = season.map(overline).unwrap_or_default();
if let Some(challenge) = stats.and_then(|s| s.challenge.as_ref()) {
use std::fmt::Write;
if !season.is_empty() {
season.push_str(" · ");
}
write!(
season,
"{} / {} validés",
challenge.completed, challenge.total
)
.unwrap();
}
let season = overline_with_count(season, stats);
let detail = if !known {
Line::plain(UNKNOWN_ANVIL)
} else if stats.is_some() {
@@ -153,7 +202,10 @@ impl BannerContent {
},
detail,
last_match,
splash: last.and_then(|row| row.splash.clone()).map(Rc::new),
splash: challenge
.last_match
.and_then(|m| row(m.champion_id)?.splash.clone())
.map(Rc::new),
}
}
}
+134
View File
@@ -0,0 +1,134 @@
//! What the banner drawn says and shows at rest: its text, the ring's ticks and the lit one, and
//! the illustration of each screen that has a banner.
use super::BannerContent;
use crate::page::{Page, Tab};
use crate::ring::{self, Tick};
use arena_tracker_core::Splash;
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// The banner's text and the ring's ticks, for when the home statistics change. Neither
/// follows the Format, the filter, the search nor the sort.
pub(in crate::page) fn prepare_banner(&mut self, cx: &mut Context<Self>) {
let stats = self.home_statistics();
let champ_select = self.in_champ_select();
let splashes = stats
.filter(|_| champ_select)
.into_iter()
.flat_map(|s| &s.rows)
.filter_map(|row| Some((row.champion.id, Rc::new(row.splash.clone()?))))
.collect();
let ticks: Rc<[Tick]> = stats
.and_then(|s| {
Some(ring::ticks(
&s.rows,
&s.challenge.as_ref()?.completion_order,
))
})
.unwrap_or_default()
.into();
self.banner = BannerContent::new(self.home_season.as_ref(), stats);
self.name_other_account();
self.champ_select_splashes = splashes;
self.reaim();
self.ring.update(cx, |ring, cx| ring.set_ticks(ticks, cx));
if self.shown_tab == Tab::InGame {
// « En partie » reads the same statistics, prepared only while shown (rule #1).
self.prepare_in_game(cx);
}
self.dress_banner(cx);
}
/// What the banner drawn says: the champ select's on « Sélection », the Live Match's on
/// « En partie », else the home's.
pub(in crate::page) fn shown_banner(&self) -> &BannerContent {
match self.shown_tab {
Tab::ChampSelect => &self.champ_select_banner,
Tab::InGame => &self.in_game.banner,
_ => &self.banner,
}
}
/// The ring and the illustration of the banner drawn. The champ select's dims the ticks
/// without an anvil and shows the card hovered; the Live Match's lights its champion's tick
/// and shows its splash; the home's dims none and shows its own splash; « Parties » lights
/// its chosen Match's champion and shows its splash. The end of a Match holds the banner of
/// the screen it plays on: its animation draws it.
pub(in crate::page) fn dress_banner(&mut self, cx: &mut Context<Self>) {
let selecting = self.shown_tab == Tab::ChampSelect;
let anvil = (self.live_champ_select())
.filter(|_| selecting)
.and_then(|pick| pick.anvil_champions.as_deref());
self.ring.update(cx, |ring, cx| ring.set_anvil(anvil, cx));
let playing = self.shown_tab == Tab::InGame;
let browsing = self.shown_tab == Tab::Matches;
let held = self.playback.active() && (self.playback.on_matches || !browsing);
// Elsewhere only a card under the pointer lights a tick.
let aimed = self
.ring_hover
.aimed
.as_ref()
.map(|aimed| (aimed.id, aimed.splash.clone()));
let lit = if let Some((id, _)) = &aimed {
Some(Some(*id))
} else if playing {
Some(self.in_game.champion)
} else if browsing {
Some(self.banner_champion().filter(|_| !held))
} else {
self.lit_by.is_none().then_some(None)
};
if let Some(lit) = lit {
self.ring.update(cx, |ring, cx| ring.set_lit(lit, cx));
}
if let Some((_, splash)) = aimed {
self.banner_art
.update(cx, |art, cx| art.set_target(splash, cx));
} else if selecting {
self.select_art(self.ring.read(cx).lit(), cx);
} else if playing {
let splash = self.in_game.banner.splash.clone();
self.banner_art
.update(cx, |art, cx| art.set_target(splash, cx));
} else if !held {
let splash = self.banner_splash();
self.banner_art
.update(cx, |art, cx| art.set_target(splash, cx));
}
}
/// The champion the banner drawn is about: the last Match's on « Défi », the Match chosen's
/// on « Parties », none when no Match is.
pub(in crate::page) fn banner_champion(&self) -> Option<u32> {
if self.shown_tab == Tab::Matches {
return Some(self.chosen_champion().0).filter(|&id| id != 0);
}
let last = self.home_statistics()?.challenge.as_ref()?.last_match;
last.map(|m| m.champion_id)
}
/// The illustration of the banner at rest: the splash of its champion.
pub(in crate::page) fn banner_splash(&self) -> Option<Rc<Splash>> {
if self.shown_tab != Tab::Matches {
return self.banner.splash.clone();
}
let id = self.banner_champion()?;
let rows = &self.home_statistics()?.rows;
Some(Rc::new(
rows.iter().find(|r| r.champion.id == id)?.splash.clone()?,
))
}
/// The illustration of the champ select's banner: the card hovered's, else its own.
pub(in crate::page) fn select_art(&self, hovered: Option<u32>, cx: &mut Context<Self>) {
let splash = match (&self.ring_hover.aimed, hovered) {
(Some(aimed), _) => aimed.splash.as_ref(),
(None, Some(id)) => self.champ_select_splashes.get(&id),
(None, None) => self.champ_select_banner.splash.as_ref(),
};
self.banner_art
.update(cx, |art, cx| art.set_target(splash.cloned(), cx));
}
}
+7 -3
View File
@@ -1,4 +1,4 @@
use super::Page;
use super::{Page, Tab};
use crate::card_grid::{CardGrid, CardHovered, PutDown};
use crate::card_lift::{Changes, Changing};
use crate::motion::MatchEnd;
@@ -149,8 +149,12 @@ impl Page {
if id.is_none() && grid == self.home_grid.entity_id() {
self.release_home(cx);
}
self.ring.update(cx, |ring, cx| ring.set_lit(id, cx));
if self.in_champ_select() {
// The pointer cannot be on a card and on the ring, but one's leaving may come after the
// other's entering.
let aimed = self.ring_hover.aimed.as_ref().map(|aimed| aimed.id);
self.ring
.update(cx, |ring, cx| ring.set_lit(id.or(aimed), cx));
if self.shown_tab == Tab::ChampSelect {
self.select_art(id, cx);
}
}
+316
View File
@@ -0,0 +1,316 @@
//! « En partie » (#109): the tab of the Live Match's phase. It shows the champion played and what
//! the Match can bring it in the Challenge: the banner with its splash, its tick of the ring lit
//! and the stake, the figures of its card's sheet and its latest Matches of the Season. « La
//! phase décide »: the start of a Live Match shows it, its end shows « Parties » (its
//! end-of-game block, #129) or « Défi ».
use super::matches::Outcome;
use super::{LiveMatchStarted, Page, Tab, home::BannerContent};
use crate::card::sheet_lines;
use crate::text::ordinal;
use crate::worker::{MatchEntry, RecentQuery, spawn_recent_matches};
use arena_tracker_core::{FollowedMatch, LiveMatch};
use gpui_kit::*;
mod render;
/// What « En partie » shows, prepared while it is shown, when the Live Match or the statistics
/// change: nothing is looked up while drawing.
#[derive(Default)]
pub(in crate::page) struct InGame {
/// The Season and the Challenge's count, the champion, and what a top 1 would bring.
pub(in crate::page) banner: BannerContent,
/// The champion played, once the client said it: its tick of the ring is lit.
pub(in crate::page) champion: Option<u32>,
/// « Première Partie avec X cette Saison », for a champion without a Match in it.
first_match: SharedString,
/// The figures of its card's sheet; empty while its row is not known.
sheet: Vec<(&'static str, SharedString)>,
recent: Recent,
/// What `recent` was asked for.
asked: Option<RecentQuery>,
/// The stored Matches changed since `recent` was asked for: a new one, or a Provisional one
/// Riot published.
stale: bool,
/// Of the latest request for `recent`: an older answer is dropped.
generation: u64,
}
impl InGame {
/// Forgets what it showed. The requests keep their count, so that an answer to one made
/// before is still dropped.
pub(in crate::page) fn clear(&mut self) {
*self = InGame {
generation: self.generation,
..InGame::default()
};
}
/// The stored Matches may have changed: the latest are read again the next time
/// « En partie » is prepared.
pub(in crate::page) fn matches_changed(&mut self) {
self.stale = true;
}
}
/// The champion's latest Matches of the Season.
#[derive(Default)]
enum Recent {
#[default]
Loading,
Ready(Vec<RecentMatch>),
Failed(SharedString),
}
/// One of the champion's latest Matches, written when it arrives.
struct RecentMatch {
when: SharedString,
placement: SharedString,
outcome: Outcome,
provisional: bool,
format: SharedString,
}
#[cfg(test)]
impl InGame {
/// The latest Matches were read, or failed to be.
pub(in crate::page) fn recent_read(&self) -> bool {
!matches!(self.recent, Recent::Loading)
}
/// The latest Matches as (when, Placement, Format, provisional); `None` until read.
pub(in crate::page) fn recent_lines(&self) -> Option<Vec<(String, String, String, bool)>> {
match &self.recent {
Recent::Ready(matches) => Some(
(matches.iter())
.map(|m| {
let text = |s: &SharedString| s.to_string();
(
text(&m.when),
text(&m.placement),
text(&m.format),
m.provisional,
)
})
.collect(),
),
_ => None,
}
}
pub(in crate::page) fn sheet(&self) -> &[(&'static str, SharedString)] {
&self.sheet
}
/// How many times the latest Matches were asked for.
pub(in crate::page) fn requests(&self) -> u64 {
self.generation
}
}
impl From<MatchEntry> for RecentMatch {
fn from(entry: MatchEntry) -> RecentMatch {
RecentMatch {
when: entry.when.into(),
placement: ordinal(entry.placement).into(),
outcome: Outcome::of(entry.placement, entry.win),
provisional: entry.provisional,
format: entry.format.name().into(),
}
}
}
impl Page {
pub(in crate::page) fn in_live_match(&self) -> bool {
self.live_match.is_some()
}
/// A champ select or a Live Match runs: the page is about the Account signed in to the
/// client and the current Season.
pub(in crate::page) fn in_phase(&self) -> bool {
self.in_champ_select() || self.in_live_match()
}
/// Whether « En partie » is in the top bar: during the Live Match, once the champ select
/// that launched it has ended.
pub(in crate::page) fn has_in_game_tab(&self) -> bool {
self.in_live_match() && !self.in_champ_select()
}
/// The Live Match the client reports changed: it started, its champion became known, or
/// the client left it. Only the client's events get here: no polling.
pub(in crate::page) fn change_live_match(
&mut self,
live: Option<LiveMatch>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(live) = live else {
// Out of the game: the next one shows again.
self.match_over = None;
if let Some(ended) = self.leave_live_match(window, cx)
&& !self.in_champ_select()
{
self.game_ended_without_block(ended.game_id, window, cx);
}
self.leave_gone_tab(window, cx);
return;
};
// Its end-of-game block already made it a Match.
if (self.match_over.as_ref()).is_some_and(|over| over.game_id == live.game_id) {
return;
}
let game = live.game_id;
let started = (self.live_match.as_ref()).is_none_or(|shown| shown.game_id != game);
self.live_match = Some(live);
if !started {
// Its champion identified (Bravery): the screen follows, when shown.
if self.shown_tab == Tab::InGame {
self.prepare_in_game(cx);
self.dress_banner(cx);
}
return;
}
if game.is_some() && self.decided_game == game {
// The client left the game and came back to it (« Reconnect »): the game had not
// ended, and its real end decides again.
self.decided_game = None;
}
cx.emit(LiveMatchStarted);
if self.in_champ_select() {
// The champ select that launched the game ends next, and its end shows
// « En partie » (`change_champ_select`).
return;
}
self.show_account(None, window, cx);
// The phase decides: « En partie » shows, from wherever the player was.
self.set_tab(Tab::InGame, window, cx);
}
/// The Live Match ended while « En partie » was chosen, and nothing chose another screen (a
/// block of another Account, a game whose end was decided already): « Défi » shows rather
/// than a tab the top bar no longer has.
pub(in crate::page) fn leave_gone_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.tab == Tab::InGame && !self.has_in_game_tab() {
self.set_tab(Tab::Challenge, window, cx);
}
}
/// The Live Match is over: its tab goes, and the home's Account and Season come back. The
/// Live Match that was, if any.
fn leave_live_match(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<LiveMatch> {
let live = self.live_match.take()?;
if !self.in_champ_select() {
// An animation asked for during it plays on the home.
self.playback.stats_pending = self.playback.active();
self.show_account(None, window, cx);
}
if self.shown_tab != Tab::InGame {
// Shown, the screen keeps what it showed until it is left (`show_tab`).
self.in_game.clear();
}
Some(live)
}
/// A round reported `followed`: the end-of-game block of the Live Match's game made it a
/// Match, and its tab goes now rather than at the lobby; what the end shows is the block's
/// (#129). Whether the statistics were asked for again.
pub(in crate::page) fn end_live_match_with_block(
&mut self,
followed: &[FollowedMatch],
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
let Some(live) = &self.live_match else {
return false;
};
let game = live.game_id;
let its_block = followed
.iter()
.any(|m| m.provisional && (m.game_id.is_none() || game.is_none() || m.game_id == game));
if !its_block {
return false;
}
self.match_over = self.leave_live_match(window, cx);
true
}
/// Prepares what « En partie » shows from the Live Match and the home statistics, which are
/// the Account's in the current Season during it; asks for the champion's latest Matches
/// when they may have changed. Only while it is shown (rule #1), the caller dressing the
/// banner. Once the Live Match is over, the screen keeps what it showed until it is left.
pub(in crate::page) fn prepare_in_game(&mut self, cx: &mut Context<Self>) {
let Some(live) = &self.live_match else {
return;
};
let champion = live.champion_id;
let stats = self.home_statistics();
let row = champion
.and_then(|id| stats.and_then(|s| s.rows.iter().find(|row| row.champion.id == id)));
let banner =
BannerContent::in_game(self.home_season.as_ref(), stats, champion.is_some(), row);
let first_match = row.map_or_else(SharedString::default, |row| {
format!("Première Partie avec {} cette Saison", row.champion.name).into()
});
let sheet = row.map(sheet_lines).unwrap_or_default();
// Asked with the statistics, which each change of the stored Matches brings again.
let asked = (stats.is_some())
.then(|| {
Some(RecentQuery {
puuid: self.displayed()?.puuid.clone(),
champion_id: champion?,
season: self.home_season.as_ref()?.to_string(),
})
})
.flatten();
self.in_game.banner = banner;
self.in_game.champion = champion;
self.in_game.first_match = first_match;
self.in_game.sheet = sheet;
if let Some(asked) = asked
&& (self.in_game.stale || self.in_game.asked.as_ref() != Some(&asked))
{
self.ask_recent(asked, cx);
}
cx.notify();
}
/// Reads the champion's latest Matches on a below-normal worker.
fn ask_recent(&mut self, asked: RecentQuery, cx: &mut Context<Self>) {
let in_game = &mut self.in_game;
in_game.generation += 1;
in_game.stale = false;
// The Matches of another Account, champion or Season are not shown meanwhile; those
// of the same are, until the new ones come.
if in_game.asked.as_ref() != Some(&asked) {
in_game.recent = Recent::Loading;
}
in_game.asked = Some(asked.clone());
spawn_recent_matches(
self.tracker.clone(),
asked,
in_game.generation,
self.tx.clone(),
);
cx.notify();
}
/// The champion's latest Matches arrived: those of the latest request only.
pub(in crate::page) fn apply_recent(
&mut self,
generation: u64,
matches: Result<Vec<MatchEntry>, String>,
) {
if generation != self.in_game.generation || self.in_game.asked.is_none() {
return;
}
self.in_game.recent = match matches {
Ok(matches) => Recent::Ready(matches.into_iter().map(RecentMatch::from).collect()),
Err(error) => Recent::Failed(error.into()),
};
}
}
+144
View File
@@ -0,0 +1,144 @@
use super::{InGame, Recent, RecentMatch};
use crate::page::home::notice_line;
use crate::page::{Page, shown};
use crate::theme::{gold_ink, heading, surface};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::*;
/// What stands for the latest Matches while they are read.
const LOADING: &str = "Chargement des Parties…";
impl Page {
/// « En partie »: the banner of the Live Match, then the champion's sheet and its latest
/// Matches of the Season side by side (one above the other in a narrow window). The column
/// scrolls in a low window, as the home's does.
pub(in crate::page) fn in_game_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let mut column = self.banner_column(window, cx);
let theme = cx.theme();
match self.stats_notice() {
// The header already says there is no Season, and a banner the statistics' error.
Some(notice) if notice.said_elsewhere() => {}
Some(notice) => {
column = column.child(notice_line(
"in-game-notice",
notice.label(self.error().map(String::as_str)),
theme.muted_foreground,
));
}
None if shown("in-game-details") && !self.in_game.sheet.is_empty() => {
column = column.child(details(&self.in_game, cx));
}
None => {}
}
vec![column.id("in-game").overflow_y_scroll().into_any_element()]
}
}
/// The champion's sheet, then its latest Matches.
fn details(in_game: &InGame, cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.h_flex()
.flex_wrap()
.items_start()
.gap_3()
.child(
panel("Fiche du champion", "in-game-sheet", cx).children(in_game.sheet.iter().map(
|(label, value)| {
line(theme)
.debug_selector(move || format!("in-game-sheet-{label}"))
.child(div().text_color(theme.muted_foreground).child(*label))
.child(div().font_weight(FontWeight::SEMIBOLD).child(value.clone()))
},
)),
)
.child(
panel("Dernières Parties de la Saison", "in-game-recent", cx)
.children(recent(in_game, theme)),
)
}
/// A titled panel of the screen: the two share the width, or wrap one above the other.
fn panel(title: &'static str, selector: &'static str, cx: &App) -> Div {
let theme = cx.theme();
div()
.v_flex()
.flex_1()
.min_w(px(280.))
.gap_2()
.p_4()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded(px(12.))
.debug_selector(move || selector.into())
.child(heading(cx).mb_1().text_lg().child(title))
}
/// One line of a panel: its label left, its value right.
fn line(theme: &Theme) -> Div {
div()
.h_flex()
.justify_between()
.items_center()
.gap_3()
.py_1()
.border_b_1()
.border_color(theme.border)
.text_sm()
}
/// The lines of the latest Matches, or what stands for them.
fn recent(in_game: &InGame, theme: &Theme) -> Vec<AnyElement> {
let muted = theme.muted_foreground;
match &in_game.recent {
Recent::Loading => vec![notice_line("in-game-recent-loading", LOADING.into(), muted)],
Recent::Failed(error) => vec![notice_line("in-game-recent-error", error.clone(), muted)],
Recent::Ready(matches) if matches.is_empty() => vec![notice_line(
"in-game-first-match",
in_game.first_match.clone(),
muted,
)],
Recent::Ready(matches) => (matches.iter().enumerate())
.map(|(ix, played)| recent_line(ix, played, theme).into_any_element())
.collect(),
}
}
/// A Match: when it started and its Format, then its Placement in the colour of its result, as
/// in « Parties ».
fn recent_line(ix: usize, played: &RecentMatch, theme: &Theme) -> Div {
let ink = played.outcome.ink(theme);
line(theme)
.debug_selector(move || format!("in-game-recent-{ix}"))
.child(
div().v_flex().min_w_0().child(played.when.clone()).child(
div()
.text_xs()
.text_color(theme.muted_foreground)
.child(played.format.clone()),
),
)
.child(
div()
.v_flex()
.items_end()
.flex_shrink_0()
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.text_color(ink)
.child(played.placement.clone()),
)
.children(played.provisional.then(|| {
div()
.text_xs()
.text_color(gold_ink(theme))
.child("Provisoire")
})),
)
}
+6 -1
View File
@@ -24,6 +24,7 @@ impl Page {
.update(cx, |art, cx| art.release(window, cx));
self.table
.update(cx, |table, cx| table.release_images(window, cx));
self.release_matches_images(window, cx);
}
/// The page is back in front of « Paramètres ».
@@ -33,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());
}
+43
View File
@@ -0,0 +1,43 @@
//! The page's text link « ‹ Défi » on the statistics page (the banner's « Statistiques » is an
//! icon button, see `home::banner`). A real button, so the keyboard reaches it (Tab, then Enter
//! or Space).
use super::Tab;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use super::Page;
impl Page {
/// A link that opens `tab`, in `ink` over the surface it stands on. Always bordered, so the
/// focus ring does not shift the label. Its hover style redraws the page, never a cached
/// view (rule #1). The caller may restyle the button it gets back.
pub(super) fn tab_link(
&self,
id: &'static str,
label: &'static str,
tab: Tab,
ink: Hsla,
cx: &mut Context<Self>,
) -> BaseButton {
let theme = cx.theme();
let (ring, hover, hover_foreground) = (theme.ring, theme.accent, theme.accent_foreground);
BaseButton::new(id)
.self_start()
.px_2()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.text_color(ink)
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label(label)
.debug_selector(|| id.into())
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}
}
+497
View File
@@ -0,0 +1,497 @@
//! « Parties »: the stored Matches of the Account chosen in the top bar, newest first, and beside
//! them the Match Recap of the one chosen. The list is read on a worker when the screen shows (or
//! the stored Matches change while it does), and only the Match chosen is decoded, on a worker
//! too: nothing runs while the screen is hidden but marking the list stale (rule #1).
mod auto_open;
mod bubble;
mod damage;
mod damage_view;
mod death;
mod details;
mod details_view;
mod filters;
#[cfg(test)]
mod inspect;
mod list;
mod recap;
mod screen;
mod shown;
mod unfolded;
pub(in crate::page) use damage::Death;
#[cfg(test)]
pub(in crate::page) use damage::{NONE_SEEN, OTHERS, ShownDamage};
use filters::Filters;
use list::MatchChosen;
pub(in crate::page) use list::MatchList;
#[cfg(test)]
pub(in crate::page) use list::MatchRow as Row;
pub(in crate::page) use list::Outcome;
pub use list::init;
#[cfg(test)]
pub(in crate::page) use recap::{augment_selector, item_selector};
#[cfg(test)]
pub(in crate::page) use shown::{AWAITED, Described, ShownPlayer, Slot, UNAVAILABLE};
use shown::{Champions, ShownRecap};
use super::{Page, Tab};
use crate::worker::{MatchEntry, RefreshGate, spawn_match_list, spawn_recap};
use arena_tracker_core::{DeathRecapState, GameCatalog, MatchRecap, Season};
use gpui_kit::component::input::InputEvent;
use gpui_kit::*;
use std::sync::Arc;
/// The recap beside the list.
pub(in crate::page) enum Recap {
/// No Match chosen.
None,
/// The Match chosen is being decoded.
Loading {
center_player: bool,
},
/// The Match is no longer stored.
Missing,
Failed(SharedString),
Ready {
recap: Box<MatchRecap>,
pane: Entity<recap::RecapPane>,
/// The Death Recaps of the Match (#128): what the details show of them.
death: Death,
},
}
/// The state of « Parties ».
pub(in crate::page) struct Matches {
/// Its own view: the selection, the scrolling and the hover.
pub(in crate::page) list: Entity<MatchList>,
/// The Account the list is of.
puuid: Option<String>,
/// Its Matches, newest first; `None` until the first list of that Account arrives.
entries: Option<Vec<MatchEntry>>,
/// The positions in `entries` of the Matches the filters keep, as the list shows them.
visible: Vec<usize>,
/// The filters of the screen that « Statistiques » does not share.
filters: Filters,
/// Why the last list failed: the Matches already known stay.
error: Option<SharedString>,
/// The stored Matches may have changed since the list was read.
stale: bool,
job: RefreshGate,
generation: u64,
/// The Match chosen. Not kept from one opening of the screen to the next.
pub(in crate::page) selected: Option<String>,
/// The Match whose end opened the screen, chosen once the list holds it (#129).
pub(in crate::page) arriving: Option<String>,
pub(in crate::page) recap: Recap,
recap_job: RefreshGate,
recap_generation: u64,
/// The Match whose Death Recap is being asked of Riot: asked once, however many times its
/// recap is decoded meanwhile.
death_fetching: Option<String>,
/// A Death Recap read is running: at most one at a time.
death_running: bool,
/// The read that waits for it (`true`: asks Riot first); only the latest is kept.
death_next: Option<(MatchRecap, bool)>,
/// The names and icons of the items and augments, from the cache on disk.
catalog: Arc<GameCatalog>,
/// In a narrow window, the list is open over the recap.
pub(in crate::page) list_open: bool,
/// The list was in the last frame: once it is not, its portraits are given back.
list_drawn: std::cell::Cell<bool>,
_chosen: Subscription,
_searched: Subscription,
}
impl Matches {
/// `seasons`: the Season table, which says what Season each Match is of.
pub(in crate::page) fn new(
seasons: &[Season],
window: &mut Window,
cx: &mut Context<Page>,
) -> Matches {
let list = cx.new(MatchList::new);
let chosen = cx.subscribe(&list, |page, _, event: &MatchChosen, cx| {
page.choose_match(event.match_id.clone(), event.close, cx)
});
let filters = Filters::new(seasons, window, cx);
let searched = cx.subscribe(&filters.input, |page, _, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
page.matches_searched(cx);
}
});
Matches {
list,
puuid: None,
entries: None,
visible: Vec::new(),
filters,
error: None,
stale: true,
job: RefreshGate::default(),
generation: 0,
selected: None,
arriving: None,
recap: Recap::None,
recap_job: RefreshGate::default(),
recap_generation: 0,
death_fetching: None,
death_running: false,
death_next: None,
catalog: Arc::default(),
list_open: false,
list_drawn: std::cell::Cell::new(false),
_chosen: chosen,
_searched: searched,
}
}
}
impl Page {
/// The stored Matches or the Account may have changed. The list follows the
/// Account chosen at once, never mixing two Accounts' Matches, and is read again while it
/// shows; hidden, it is only marked stale.
pub(in crate::page) fn matches_changed(&mut self, cx: &mut Context<Self>) {
let puuid = self.viewed().map(|a| a.puuid.clone());
let matches = &mut self.matches;
if puuid != matches.puuid {
matches.puuid = puuid;
matches.entries = None;
matches.visible.clear();
matches.error = None;
matches.selected = None;
matches.arriving = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
matches.list_open = false;
matches
.list
.update(cx, |list, cx| list.set_rows(Vec::new(), None, cx));
}
matches.stale = true;
if self.shown_tab == Tab::Matches {
self.request_matches();
}
self.in_game.matches_changed();
}
/// Reads the list on a worker, or queues the reading behind the one running: an earlier
/// result is stale.
fn request_matches(&mut self) {
let matches = &mut self.matches;
matches.stale = false;
matches.generation += 1;
if matches.puuid.is_some() && matches.job.request() {
self.spawn_match_list();
}
}
/// Starts the reading the gate let through; none while the screen is hidden.
fn spawn_match_list(&mut self) {
match self.matches.puuid.clone() {
Some(puuid) if self.shown_tab == Tab::Matches => spawn_match_list(
self.tracker.clone(),
puuid,
self.matches.generation,
self.tx.clone(),
),
_ => self.matches.job.reset(),
}
}
/// The screen arrives: the list is read again if the stored Matches changed, and the most
/// recent Match the filters keep is chosen, the previous choice forgotten.
pub(in crate::page) fn open_matches(&mut self, cx: &mut Context<Self>) {
let matches = &mut self.matches;
matches.selected = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
matches.list_open = false;
matches.list.update(cx, |list, _| list.scroll_to_top());
if matches.stale || matches.entries.is_none() {
// The most recent is chosen when the list arrives.
self.request_matches();
}
// Else the most recent is chosen with the list written.
self.dress_matches(cx);
}
/// The screen leaves: the recap goes, and the portraits of both sides. A list or a recap
/// still being read is dropped, and nothing queued starts.
pub(in crate::page) fn close_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.release_matches_images(window, cx);
let matches = &mut self.matches;
// The list is read again at the next opening only if it may be out of date: a read cut
// short here, or one that failed. Stored data that changes meanwhile marks it too.
matches.stale |= matches.job.running() || matches.error.is_some();
matches.generation += 1;
matches.selected = None;
matches.arriving = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
// The read running ends by itself; none starts after it.
matches.death_next = None;
}
pub(in crate::page) fn release_matches_images(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.matches
.list
.update(cx, |list, cx| list.release_images(window, cx));
if let Recap::Ready { pane, .. } = &self.matches.recap {
pane.read(cx)
.images
.clone()
.update(cx, |images, cx| images.release(window, cx));
}
}
/// A list read by the worker.
pub(in crate::page) fn apply_matches(
&mut self,
generation: u64,
result: Result<Vec<MatchEntry>, String>,
window: &Window,
cx: &mut Context<Self>,
) {
if generation == self.matches.generation {
match result {
Ok(entries) => {
self.show_matches(entries, cx);
// The Match the end of a game opened is chosen: its animation may play.
self.play_waiting(window, cx);
}
// The Matches already known stay.
Err(error) => self.matches.error = Some(error.into()),
}
}
if self.matches.job.finished() {
self.spawn_match_list();
}
}
fn show_matches(&mut self, entries: Vec<MatchEntry>, cx: &mut Context<Self>) {
let matches = &mut self.matches;
matches.error = None;
let previous = matches.entries.replace(entries).unwrap_or_default();
let entries = matches.entries.as_deref().unwrap_or_default();
auto_open::forget_unlisted(&mut matches.arriving, entries);
// The Match chosen stays chosen while it is listed and kept by the filters, as a sync
// lists them again; the filters choose another when it is not.
let corrected = (matches.selected.as_ref())
.and_then(|id| entries.iter().find(|entry| entry.match_id == *id))
// Published or corrected meanwhile: decoded again.
.is_some_and(|entry| !previous.contains(entry));
// A decoding that failed is tried again as the list is read again.
let failed = matches!(matches.recap, Recap::Failed(_))
&& (matches.selected.as_ref())
.is_some_and(|id| entries.iter().any(|entry| entry.match_id == *id));
if corrected || failed {
let center = matches!(
matches.recap,
Recap::Loading {
center_player: true
}
);
self.request_recap(center);
}
self.dress_matches(cx);
}
/// The list chose a Match: its recap is decoded.
fn choose_match(&mut self, match_id: String, close: bool, cx: &mut Context<Self>) {
if close {
self.matches.list_open = false;
}
// The player's choice comes first.
self.matches.arriving = None;
if self.matches.selected.as_deref() != Some(match_id.as_str()) {
self.matches.selected = Some(match_id);
self.request_recap(true);
} else {
match &mut self.matches.recap {
Recap::Loading { center_player } => *center_player = true,
Recap::Ready { pane, .. } => pane.update(cx, |pane, cx| {
pane.center_player = true;
cx.notify();
}),
_ => {}
}
}
self.dress_banner(cx);
cx.notify();
}
/// Decodes the Match chosen on a worker, one at a time: a choice made meanwhile is decoded
/// once it reports, and its result dropped.
fn request_recap(&mut self, center_player: bool) {
let matches = &mut self.matches;
matches.recap_generation += 1;
let Some(selected) = &matches.selected else {
matches.recap = Recap::None;
return;
};
// The same Match decoded again keeps its recap until the new one arrives.
let same =
matches!(&matches.recap, Recap::Ready { recap, .. } if recap.match_id == *selected);
if !same {
matches.recap = Recap::Loading { center_player };
}
if matches.recap_job.request() {
self.spawn_recap();
}
}
/// Starts the decoding the gate let through; none while the screen is hidden.
fn spawn_recap(&mut self) {
let matches = &self.matches;
match (&matches.puuid, &matches.selected) {
(Some(puuid), Some(selected)) if self.shown_tab == Tab::Matches => spawn_recap(
self.tracker.clone(),
puuid.clone(),
selected.clone(),
matches.catalog.clone(),
matches.recap_generation,
self.tx.clone(),
),
_ => self.matches.recap_job.reset(),
}
}
/// A Match Recap decoded by the worker.
pub(in crate::page) fn apply_recap(
&mut self,
generation: u64,
result: Result<Option<MatchRecap>, String>,
death: Result<DeathRecapState, String>,
catalog: &Arc<GameCatalog>,
cx: &mut Context<Self>,
) {
if generation == self.matches.recap_generation {
self.matches.recap = match result {
Ok(Some(recap)) => {
// What the same Match showed before, when it is decoded again.
let (existing, open, previous) = match &self.matches.recap {
Recap::Ready {
recap: old,
pane,
death,
..
} if old.match_id == recap.match_id => (
Some(pane.clone()),
// A corrected Placement may move the player: followed, else folded.
pane.read(cx)
.open
.and_then(|open| unfolded::same_player(old, open, &recap)),
Some(death.clone()),
),
_ => (None, None, None),
};
let death = self.death_on_arrival(&recap, death, previous.as_ref());
let champions = self.champions();
let catalog = self.matches.catalog.clone();
let shown = ShownRecap::new(
&recap,
self.chosen_champion(),
&champions,
&catalog,
&death,
);
let pane = if let Some(pane) = existing {
pane.update(cx, |pane, cx| {
pane.open = open;
pane.shown = shown;
cx.notify();
});
pane
} else {
let center = matches!(
self.matches.recap,
Recap::Loading {
center_player: true
}
);
recap::RecapPane::new(shown, center, cx)
};
Recap::Ready {
recap: Box::new(recap),
pane,
death,
}
}
Ok(None) => Recap::Missing,
Err(error) => Recap::Failed(format!("Récapitulatif indisponible : {error}").into()),
};
// Matched to a catalog that the game data replaced meanwhile: read again.
if !Arc::ptr_eq(catalog, &self.matches.catalog) {
self.death_recap_matched_again();
}
}
if self.matches.recap_job.finished() {
self.spawn_recap();
}
cx.notify();
}
/// The champions' names and portraits, as the statistics have them.
fn champions(&self) -> Champions {
Champions::of(self.home_statistics().or(self.stats.as_ref()))
}
/// The champion of the Match chosen, from its row.
pub(in crate::page) fn chosen_champion(&self) -> (u32, &str) {
let matches = &self.matches;
(matches.entries.iter().flatten())
.find(|entry| Some(&entry.match_id) == matches.selected.as_ref())
.map_or((0, ""), |e| (e.champion_id, e.champion_name.as_str()))
}
/// Keeps the Matches the filters leave, writes the rows of the list and the recap with the
/// champions' names and portraits, which the statistics may bring after the Matches, and
/// chooses the first Match kept when the one chosen is not.
pub(in crate::page) fn dress_matches(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Matches && self.tab != Tab::Matches {
return;
}
let champions = self.champions();
self.refilter(&champions, cx);
self.rewrite_recap(&champions, cx);
}
/// New names and icons for the items and augments: the recap shown is written again.
pub(in crate::page) fn apply_game_data(
&mut self,
catalog: Arc<GameCatalog>,
cx: &mut Context<Self>,
) {
self.matches.catalog = catalog;
// A hidden screen holds no recap: the next one decoded has them.
if matches!(self.matches.recap, Recap::Ready { .. }) {
let champions = self.champions();
self.rewrite_recap(&champions, cx);
// The Death Recap is matched to the new names.
self.death_recap_matched_again();
cx.notify();
}
}
/// Writes the recap shown again, with the champions and the catalog as they are now.
fn rewrite_recap(&mut self, champions: &Champions, cx: &mut Context<Self>) {
let champion = self.chosen_champion();
let champion = (champion.0, champion.1.to_string());
let catalog = self.matches.catalog.clone();
if let Recap::Ready {
recap, pane, death, ..
} = &mut self.matches.recap
{
pane.update(cx, |pane, cx| {
pane.shown =
ShownRecap::new(recap, (champion.0, &champion.1), champions, &catalog, death);
cx.notify();
});
}
}
}
+162
View File
@@ -0,0 +1,162 @@
//! The end of a Match opens its recap (#129): when its end-of-game block arrives, « Parties »
//! shows the new Match, from any screen, never bringing the window forward nor taking the focus.
//! With the preference off, or when the game ended without a block, the Challenge shows instead.
//! The animation of the end of the Match plays on « Parties » then (#110). Each game's end is
//! decided once: nothing brings the player back to either screen afterwards.
//! During a Live Match, « En partie » stays until the block or the lobby (#109).
use crate::page::{ALL_SEASONS, Page, RecapOpened, Tab};
use crate::worker::MatchEntry;
use arena_tracker_core::{FollowedMatch, GameEnd, SeasonScope};
use gpui_kit::component::IndexPath;
use gpui_kit::*;
impl Page {
/// The preference changed in « Paramètres ».
pub(crate) fn set_open_recap_at_match_end(&mut self, open: bool) {
self.open_recap_at_match_end = open;
}
#[cfg(test)]
pub(crate) fn opens_recap_at_match_end(&self) -> bool {
self.open_recap_at_match_end
}
/// A round reported `followed`, and `end` when the client left an Arena game. The most
/// recent Match of the active Account whose end-of-game block arrived is shown in
/// « Parties », once the list holds it; with the preference off it shows the Challenge. A game
/// that ended without one shows the Challenge, unless its block was already decided on. A
/// Match found later on Riot's side (no block) changes nothing. Nothing during a champ
/// select, which the phase rule keeps in front.
pub(in crate::page) fn follow_match_end(
&mut self,
followed: &[FollowedMatch],
end: Option<GameEnd>,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.in_champ_select() {
return;
}
let puuid = self.active_account().map(|a| a.puuid.clone());
let arrived = (followed.iter())
.filter(|m| m.provisional && Some(&m.puuid) == puuid.as_ref())
.max_by_key(|m| m.started_at_ms);
if let Some(arrived) = arrived {
let decided = self.decided_game.is_some() && self.decided_game == arrived.game_id;
self.decided_game = arrived.game_id;
if self.open_recap_at_match_end {
// A block that comes after its game was decided on still opens its recap.
self.open_arrived_recap(arrived, window, cx);
} else if !decided {
// The end decides, as a phase does: the active Account's Challenge shows.
if self.pinned.is_some() {
self.show_account(None, window, cx);
}
self.set_tab(Tab::Challenge, window, cx);
}
return;
}
let Some(end) = end else {
return;
};
// « En partie » stays on the game's end-of-game screen: the block, or the lobby
// without one, decides then (#109).
if self.in_live_match() {
return;
}
self.game_ended_without_block(end.game_id, window, cx);
}
/// The game `game` ended without its block: « Défi » shows, once per game, from wherever
/// the player is.
pub(in crate::page) fn game_ended_without_block(
&mut self,
game: Option<u64>,
window: &mut Window,
cx: &mut Context<Self>,
) {
if game.is_none() || game != self.decided_game {
self.decided_game = game;
if self.pinned.is_some() {
self.show_account(None, window, cx);
}
self.set_tab(Tab::Challenge, window, cx);
}
}
/// Shows « Parties » with the Match `ended` chosen once the list holds it.
fn open_arrived_recap(
&mut self,
ended: &FollowedMatch,
window: &mut Window,
cx: &mut Context<Self>,
) {
// The active Account's Match shows the active Account, before the list is chosen again.
if self.pinned.is_some() {
self.show_account(None, window, cx);
}
let matches = &mut self.matches;
matches.arriving = Some(ended.match_id.clone());
// The list may not hold it yet: read again.
matches.stale = true;
// Neither the Placement nor the search of an earlier visit hides it.
matches.filters.clear(window, cx);
let hidden = match &self.season {
SeasonScope::AllSeasons => false,
SeasonScope::Season(name) => Some(name) != ended.season.as_ref(),
} || self.format.is_some_and(|format| format != ended.format);
if hidden {
self.show_every_format_of_the_season(ended.season.clone(), window, cx);
}
// The animation of the end of a Match waiting plays on this screen, not on « Défi » (#110).
self.playback.on_matches = self.playback.waiting.waiting().is_some();
let drawn = self.shown_tab == Tab::Matches;
// Hidden, minimised or behind « Paramètres », the switch is at once, without the veil.
self.set_tab(Tab::Matches, window, cx);
if drawn {
// Already drawn, the screen does not open again by itself: an earlier recap goes.
self.open_matches(cx);
}
cx.emit(RecapOpened);
}
/// The Season and Format of « Statistiques » hide the Match that just ended: to its Season
/// (all of them when none holds it) and every Format, so the new Match is the one shown.
/// The selectors are shared with « Statistiques », whose statistics follow on a worker
/// (#129).
fn show_every_format_of_the_season(
&mut self,
season: Option<String>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let (scope, name) = match season {
Some(name) => (SeasonScope::Season(name.clone()), SharedString::from(name)),
None => (SeasonScope::AllSeasons, SharedString::from(ALL_SEASONS)),
};
self.season = scope;
self.format = None;
self.season_select.update(cx, |select, cx| {
select.set_selected_value(&name, window, cx)
});
self.format_select.update(cx, |select, cx| {
select.set_selected_index(Some(IndexPath::new(0)), window, cx)
});
// A statistics job already running is for the scope left.
self.stats_generation += 1;
let start_job = self.stats_job.request();
self.recompute_in_background(start_job, window, cx);
}
}
/// A list read after the Match ended that does not hold it never will (another Account's, or
/// already gone): the screen chooses as when opened by hand.
pub(super) fn forget_unlisted(arriving: &mut Option<String>, entries: &[MatchEntry]) {
if arriving
.as_ref()
.is_some_and(|id| !entries.iter().any(|entry| entry.match_id == *id))
{
*arriving = None;
}
}
+153
View File
@@ -0,0 +1,153 @@
//! The bubble shown on hovering an item or an augment (#132, #133): its name in bold, then its
//! description in plain text, the same in the recap and in the damage seen in the Death Recaps.
//! The text is prepared once by the catalog; the bubble is built only while the hover lasts
//! (Rule #1), from two cheap clones.
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
use super::shown::Described;
/// So that a long description wraps.
const WIDTH: f32 = 320.;
const UNAVAILABLE: &str = "Description indisponible";
/// What a bubble shows.
#[derive(Clone)]
pub(super) enum Bubble {
/// An item or an augment: its name, then its description (`None`: the catalog has none).
Described {
name: SharedString,
description: Option<SharedString>,
},
/// A word alone: « Indisponible » (or « En attente ») on an item slot the source does not give.
Word(&'static str),
}
impl Bubble {
pub(super) fn of(shown: &Described) -> Bubble {
Bubble::Described {
name: shown.name.clone(),
description: shown.description.clone(),
}
}
/// The tooltip builder of an element; the bubble is built only when it opens.
pub(super) fn build(self) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
move |window, cx| match &self {
Bubble::Described { name, description } => {
let (name, description) = (name.clone(), description.clone());
Tooltip::element(move |_, cx| {
content(&name, description.as_ref(), cx.theme().muted_foreground)
})
.build(window, cx)
}
Bubble::Word(word) => Tooltip::new(*word).build(window, cx),
}
}
}
fn content(name: &SharedString, description: Option<&SharedString>, muted: Hsla) -> Div {
let body = match description {
// The text keeps its line breaks: the stats, then each passive or active.
Some(text) => div()
.debug_selector(|| "bubble-description".into())
.child(text.clone()),
None => div()
.text_color(muted)
.debug_selector(|| "bubble-unavailable".into())
.child(UNAVAILABLE),
};
div()
.v_flex()
.gap_1()
.max_w(px(WIDTH))
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.debug_selector(|| "bubble-name".into())
.child(name.clone()),
)
.child(body)
}
/// An element of a scrolled list that is laid out with the others, but painted, and given its
/// bubble, only while it shows inside the scroll mask (Rule #1).
pub(super) struct Visible {
pub div: Div,
/// Under the id of its player's line, which is unique in the recap.
pub id: (&'static str, usize),
pub bubble: Bubble,
}
impl IntoElement for Visible {
type Element = Self;
fn into_element(self) -> Self {
self
}
}
impl Element for Visible {
type RequestLayoutState = <Div as Element>::RequestLayoutState;
type PrepaintState = <Div as Element>::PrepaintState;
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
self.div.source_location()
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
inspector: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
self.div.request_layout(None, inspector, window, cx)
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
inspector: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
layout: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let visible = bounds.intersect(&window.content_mask().bounds);
if visible.size.width <= Pixels::ZERO || visible.size.height <= Pixels::ZERO {
return None;
}
self.div
.interactivity()
.tooltip(self.bubble.clone().build());
window.with_global_id(self.id.into(), |id, window| {
self.div
.prepaint(Some(id), inspector, bounds, layout, window, cx)
})
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
inspector: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
layout: &mut Self::RequestLayoutState,
hitbox: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
if hitbox.is_some() {
window.with_global_id(self.id.into(), |id, window| {
self.div
.paint(Some(id), inspector, bounds, layout, hitbox, window, cx);
});
}
}
}
+151
View File
@@ -0,0 +1,151 @@
//! The « Dégâts observés dans les récaps de mort » of a player's details (#128), written once
//! with the rest of the recap. The Match-V5 timeline is the only source of damage by effect,
//! and only for champions who died: the total of the Match per effect is not known, and what
//! was dealt to a champion who survived is never attributed.
use arena_tracker_core::{DamageSums, DeathRecapState, Effect, GameCatalog, RecapPlayer};
use gpui_kit::SharedString;
use super::shown::{AWAITED, Described, UNAVAILABLE};
use crate::text::thousands;
pub(in crate::page) const LOADING: &str = "Chargement…";
pub(in crate::page) const NONE_SEEN: &str = "Aucun dégât observé";
/// What is not one of the player's items or augments: basic attacks, champion spells, effects
/// the catalog cannot match.
pub(in crate::page) const OTHERS: &str = "Autres effets";
/// What the page knows of the Death Recaps of the Match opened.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) enum Death {
/// Riot is being asked for the timeline.
Loading,
/// The last try failed, for a reason that may pass: « Réessayer ».
Failed,
/// What is stored; `NotFetched` for a Provisional Match, which has no timeline yet.
Known(DeathRecapState),
}
/// One line: an item or an augment, or « Autres effets ».
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownEffect {
/// « Autres effets » has no icon nor description.
pub(in crate::page) described: Described,
/// The icon's place is kept even without a file: not for « Autres effets », which has no
/// bubble either.
pub(in crate::page) has_icon_slot: bool,
pub(in crate::page) total: SharedString,
/// « Physiques 120 · Magiques 80 »: the types that dealt something.
pub(in crate::page) types: SharedString,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) enum ShownDamage {
/// A word instead of values: « En attente », « Chargement… », « Indisponible » or
/// « Aucun dégât observé ».
Note(&'static str),
/// A transient failure: « Réessayer ».
Retry,
/// The player's items and augments, the most damaging first, then « Autres effets ».
Seen(Vec<ShownEffect>),
}
impl ShownDamage {
pub(super) fn of(
p: &RecapPlayer,
provisional: bool,
death: &Death,
catalog: &GameCatalog,
) -> ShownDamage {
if provisional {
return ShownDamage::Note(AWAITED);
}
let stored = match death {
Death::Failed => return ShownDamage::Retry,
// Not fetched cannot stay shown for a published Match: it is being fetched.
Death::Loading | Death::Known(DeathRecapState::NotFetched) => {
return ShownDamage::Note(LOADING);
}
Death::Known(DeathRecapState::Refused) => return ShownDamage::Note(UNAVAILABLE),
Death::Known(DeathRecapState::Stored(stored)) => stored,
};
let Some(dealt) = p.participant_id.and_then(|id| stored.player(id)) else {
return ShownDamage::Note(NONE_SEEN);
};
let mut lines: Vec<_> = (dealt.effects.iter())
.map(|entry| {
let display = match entry.effect {
Effect::Item(id) => catalog.item_display(id),
Effect::Augment(id) => catalog.augment_display(id),
};
line(display.into(), true, &entry.damage)
})
.collect();
if dealt.others.total() > 0 {
let others = Described {
name: OTHERS.into(),
description: None,
icon: None,
};
lines.push(line(others, false, &dealt.others));
}
if lines.is_empty() {
return ShownDamage::Note(NONE_SEEN);
}
ShownDamage::Seen(lines)
}
}
fn line(described: Described, has_icon_slot: bool, damage: &DamageSums) -> ShownEffect {
let types = [
("Physiques", damage.physical),
("Magiques", damage.magic),
("Bruts", damage.true_damage),
]
.iter()
.filter(|(_, sum)| *sum > 0)
.map(|(caption, sum)| format!("{caption} {}", thousands(*sum)))
.collect::<Vec<_>>()
.join(" · ");
ShownEffect {
described,
has_icon_slot,
total: thousands(damage.total()).into(),
types: types.into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn damage(provisional: bool, death: &Death) -> ShownDamage {
ShownDamage::of(
&RecapPlayer {
participant_id: Some(2),
..RecapPlayer::default()
},
provisional,
death,
&GameCatalog::default(),
)
}
#[test]
fn each_state_says_itself_in_a_word_or_a_button() {
let known = |state| Death::Known(state);
let note = |word| ShownDamage::Note(word);
// A Provisional Match waits, whatever is known.
assert_eq!(damage(true, &Death::Loading), note(AWAITED));
assert_eq!(
damage(true, &known(DeathRecapState::NotFetched)),
note(AWAITED)
);
assert_eq!(damage(false, &Death::Loading), note(LOADING));
assert_eq!(damage(false, &Death::Failed), ShownDamage::Retry);
assert_eq!(
damage(false, &known(DeathRecapState::Refused)),
note(UNAVAILABLE)
);
}
}
+160
View File
@@ -0,0 +1,160 @@
//! The section « Dégâts observés dans les récaps de mort » of a player's details, drawn for the
//! player unfolded only: one line per item or augment with its icon, name and damage, then
//! « Autres effets », or the word or button that stands for them.
use std::path::PathBuf;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::bubble::Bubble;
use super::damage::{ShownDamage, ShownEffect};
use super::recap::RecapPane;
const TITLE: &str = "Dégâts observés dans les récaps de mort";
/// Said once for the section: the timeline details only what a champion received before dying.
const NOTE: &str = "Le total de la Partie par effet est indisponible : seuls les dégâts subis avant une élimination sont détaillés. Les dégâts infligés à un champion qui survit ne sont jamais attribués.";
const ICON: f32 = 20.;
pub(super) fn section(damage: &ShownDamage, cx: &Context<RecapPane>) -> impl IntoElement {
let theme = cx.theme();
let muted = theme.muted_foreground;
div()
.v_flex()
.gap_1()
.debug_selector(|| "death-recap".into())
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(TITLE),
)
.child(match damage {
ShownDamage::Note(word) => div()
.text_sm()
.text_color(muted)
.debug_selector(|| "death-recap-note".into())
.child(*word)
.into_any_element(),
ShownDamage::Retry => retry(cx).into_any_element(),
ShownDamage::Seen(lines) => div()
.v_flex()
.gap_1()
.children(
lines
.iter()
.enumerate()
.map(|(ix, line)| effect(line, ix, theme)),
)
.into_any_element(),
})
.child(div().text_xs().text_color(muted).child(NOTE))
}
/// « Réessayer »: asks Riot again.
fn retry(cx: &Context<RecapPane>) -> impl IntoElement {
let theme = cx.theme();
let (ring, border, hover, hover_foreground) = (
theme.ring,
theme.border,
theme.accent,
theme.accent_foreground,
);
div()
.h_flex()
.items_center()
.gap_2()
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Les récaps de mort n’ont pas pu être récupérés."),
)
.child(
BaseButton::new("death-recap-retry")
.px_2()
.py_1()
.rounded_md()
.text_sm()
.border_1()
.border_color(border)
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label("Réessayer")
.debug_selector(|| "death-recap-retry".into())
.child("Réessayer")
.on_click(cx.listener(|page, _, _, cx| {
let page = page.page.clone();
cx.defer(move |cx| {
let _ = page.update(cx, |page, cx| page.retry_death_recap(cx));
});
})),
)
}
fn icon(path: Option<&PathBuf>, theme: &Theme) -> AnyElement {
match path {
Some(path) => img(path.clone())
.size(px(ICON))
.flex_shrink_0()
.rounded(px(3.))
.into_any_element(),
None => Icon::new(IconName::Frame)
.xsmall()
.text_color(theme.muted_foreground)
.into_any_element(),
}
}
/// `ix`: the line's place in its list, which names it. An item or an augment shows its bubble
/// over the whole line; « Autres effets » none.
fn effect(line: &ShownEffect, ix: usize, theme: &Theme) -> impl IntoElement {
div()
.id(("death-effect", ix))
.debug_selector(move || format!("death-effect-{ix}"))
.when(line.has_icon_slot, |row| {
row.tooltip(Bubble::of(&line.described).build())
})
.h_flex()
.items_center()
.gap_2()
.when(line.has_icon_slot, |row| {
row.child(
div()
.size(px(ICON))
.flex_shrink_0()
.flex()
.items_center()
.justify_center()
.child(icon(line.described.icon.as_ref(), theme)),
)
})
.child(
div()
.w(px(190.))
.flex_shrink_0()
.text_sm()
.overflow_hidden()
.whitespace_nowrap()
.child(line.described.name.clone()),
)
.child(
div()
.w(px(70.))
.flex_shrink_0()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.text_right()
.whitespace_nowrap()
.child(line.total.clone()),
)
.child(
div()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(line.types.clone()),
)
}
+153
View File
@@ -0,0 +1,153 @@
//! The Death Recap of the Match opened (#128): read with its recap, asked of Riot once when it
//! was never fetched (an older Match, opened for the first time), asked again on « Réessayer »,
//! and read again when the followed Match it belongs to was fetched in the background or the
//! game data changed what its effects are matched to. Nothing is fetched for a Provisional
//! Match, nor for the whole history. One read runs at a time, and only the latest waits behind
//! it: browsing the list while Riot is slow starts no more threads (rule #1).
use std::sync::Arc;
use arena_tracker_core::{DeathRecapState, GameCatalog, MatchRecap};
use gpui_kit::*;
use super::damage::Death;
use super::{Page, Recap};
use crate::worker::spawn_death_recap;
impl Page {
/// What to show of the Death Recap of `recap`, just decoded, from what was stored: the one
/// not fetched is asked for here, once, unless a request for it is still on its way.
/// `previous`: what the same Match showed before it was decoded again.
pub(super) fn death_on_arrival(
&mut self,
recap: &MatchRecap,
stored: Result<DeathRecapState, String>,
previous: Option<&Death>,
) -> Death {
match stored {
Ok(DeathRecapState::NotFetched) if recap.provisional => {
Death::Known(DeathRecapState::NotFetched)
}
Ok(DeathRecapState::NotFetched) => {
let matches = &mut self.matches;
// « Réessayer » is the user's, not asked again as the recap is decoded again.
if previous == Some(&Death::Failed) {
return Death::Failed;
}
if matches.death_fetching.as_deref() != Some(recap.match_id.as_str()) {
matches.death_fetching = Some(recap.match_id.clone());
self.spawn_death_recap(recap.clone(), true);
}
Death::Loading
}
Ok(state) => Death::Known(state),
Err(_) => Death::Failed,
}
}
/// Reads the Death Recap of `recap` on a worker (`fetch`: asks Riot first), or makes it the
/// one that waits for the read running, replacing an earlier one: it is for a Match no
/// longer shown, or the same one.
fn spawn_death_recap(&mut self, recap: MatchRecap, fetch: bool) {
let matches = &mut self.matches;
if matches.death_running {
// A wait for the same Match does not lose the request it makes of Riot.
let fetch = fetch
|| (matches.death_next.as_ref())
.is_some_and(|(next, f)| *f && next.match_id == recap.match_id);
matches.death_next = Some((recap, fetch));
return;
}
matches.death_running = true;
spawn_death_recap(
self.tracker.clone(),
recap,
matches.catalog.clone(),
fetch,
self.tx.clone(),
);
}
/// The read running reported: the one waiting starts.
fn death_read_done(&mut self) {
self.matches.death_running = false;
if let Some((recap, fetch)) = self.matches.death_next.take() {
self.spawn_death_recap(recap, fetch);
}
}
/// « Réessayer »: asks Riot again for the Death Recap of the Match opened.
pub(in crate::page) fn retry_death_recap(&mut self, cx: &mut Context<Self>) {
let Recap::Ready { recap, death, .. } = &mut self.matches.recap else {
return;
};
if *death != Death::Failed {
return;
}
*death = Death::Loading;
let recap = (**recap).clone();
self.matches.death_fetching = Some(recap.match_id.clone());
self.spawn_death_recap(recap, true);
self.rewrite_recap(&self.champions(), cx);
cx.notify();
}
/// The Death Recap read by the worker for the Match opened (an old answer for another
/// Match is dropped). One that was asked of Riot and failed offers « Réessayer »; a mere
/// read that found nothing leaves what is shown.
pub(in crate::page) fn apply_death_recap(
&mut self,
match_id: String,
fetched: bool,
result: Result<DeathRecapState, String>,
catalog: &Arc<GameCatalog>,
cx: &mut Context<Self>,
) {
self.death_read_done();
if fetched && self.matches.death_fetching.as_deref() == Some(match_id.as_str()) {
self.matches.death_fetching = None;
}
let Recap::Ready { recap, death, .. } = &mut self.matches.recap else {
return;
};
if recap.match_id != match_id || recap.provisional {
return;
}
*death = match result {
Ok(state @ (DeathRecapState::Stored(_) | DeathRecapState::Refused)) => {
Death::Known(state)
}
_ if fetched => Death::Failed,
_ => return,
};
// A fetch that began before the game data changed is matched to the old names.
if !Arc::ptr_eq(catalog, &self.matches.catalog) {
self.death_recap_matched_again();
}
self.rewrite_recap(&self.champions(), cx);
cx.notify();
}
/// The follower's queue fetched the Death Recap of a Match: shown when it is the one
/// opened and does not have it yet.
pub(in crate::page) fn death_recap_stored(&mut self, match_id: &str) {
if let Recap::Ready { recap, death, .. } = &self.matches.recap
&& recap.match_id == match_id
&& !recap.provisional
&& !matches!(death, Death::Known(_))
{
let recap = (**recap).clone();
self.spawn_death_recap(recap, false);
}
}
/// New names for the effects: a stored Death Recap is matched to them again.
pub(super) fn death_recap_matched_again(&mut self) {
if let Recap::Ready { recap, death, .. } = &self.matches.recap
&& matches!(death, Death::Known(DeathRecapState::Stored(_)))
{
let recap = (**recap).clone();
self.spawn_death_recap(recap, false);
}
}
}
+319
View File
@@ -0,0 +1,319 @@
//! The details of a player in the recap, written once with the rest of the recap: what
//! Match-V5 gives of their Match, each measure named with its scope and, off points, its unit.
//! Totals are kept as published: no value is the sum of others. A folded player builds none of
//! it on screen (rule #1).
use arena_tracker_core::{DamageByType, RecapPlayer};
use super::shown::Value;
use crate::text::{seconds, thousands};
/// One measure and its value.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Measure {
pub(in crate::page) caption: &'static str,
/// A word on what the number is, shown as the caption's tooltip.
pub(in crate::page) hint: Option<&'static str>,
pub(in crate::page) value: Value,
/// The fill of the measure's bar, in 0..=1; none when the value is absent. A damage type's
/// is its share of the types' sum; any other's, a damage total's included, its share of the
/// best of the Match. Written with the recap, never computed on screen.
pub(in crate::page) bar: Option<f32>,
}
/// Measures that go together, on one row.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Group {
pub(in crate::page) title: &'static str,
pub(in crate::page) measures: Vec<Measure>,
/// The measures after the first are the parts of one bar, the first being its total.
pub(in crate::page) split: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Details(pub(in crate::page) Vec<Group>);
impl Details {
/// `missing`: the word for a value the source does not give. `all`: every player of the
/// Match, the best of each compared measure being its full bar.
pub(super) fn of(p: &RecapPlayer, missing: &'static str, all: &[&RecapPlayer]) -> Details {
let points = |value: Option<u64>| Value::of(value, missing, thousands);
let gold =
|value: Option<u64>| Value::of(value, missing, |v| format!("{} or", thousands(v)));
let time = |value: Option<u64>| Value::of(value, missing, seconds);
// A measure and its share of the best of the Match.
let versus = |caption, read: Read, show: &dyn Fn(Option<u64>) -> Value| {
let best = all
.iter()
.filter_map(|q| read(q))
.chain(read(p))
.max()
.unwrap_or(0);
Measure {
bar: read(p).map(|v| share(v, best)),
..measure(caption, show(read(p)))
}
};
let by_type = |title, read: fn(&RecapPlayer) -> &DamageByType| {
let damage = read(p);
// One absent type would stretch the others over its part: the bar stays empty.
let sum: Option<u64> = [damage.physical, damage.magic, damage.true_damage]
.into_iter()
.sum();
let part = |caption, value: Option<u64>| Measure {
bar: sum.zip(value).map(|(sum, v)| share(v, sum)),
..measure(caption, points(value))
};
Group {
title,
measures: vec![
versus("Total", &|q| read(q).total, &points),
part("Physiques", damage.physical),
part("Magiques", damage.magic),
part("Bruts", damage.true_damage),
],
split: true,
}
};
Details(vec![
by_type(DEALT, |q| &q.damage_to_champions),
by_type("Dégâts reçus", |q| &q.damage_taken),
Group {
title: "Protection",
measures: vec![
versus("Dégâts atténués (sur soi)", &|p| p.self_mitigated, &points),
versus("Soins aux alliés", &|p| p.heals_on_teammates, &points),
versus(
"Boucliers sur les alliés",
&|p| p.shields_on_teammates,
&points,
),
],
split: false,
},
Group {
title: "Or",
measures: vec![
versus("Or gagné", &|p| p.gold_earned, &gold),
versus("Or dépensé", &|p| p.gold_spent, &gold),
],
split: false,
},
Group {
title: "Contrôle",
measures: vec![
versus("Contrôle infligé", &|p| p.total_time_cc_dealt_s, &time),
Measure {
hint: Some(SCORE_HINT),
..versus("Score de contrôle", &|p| p.time_ccing_others_s, &points)
},
],
split: false,
},
])
}
/// The value of a measure of a group, as the tests ask for it.
#[cfg(test)]
pub(in crate::page) fn get(&self, title: &str, caption: &str) -> Option<&Value> {
let group = self.0.iter().find(|group| group.title == title)?;
(group.measures.iter())
.find(|measure| measure.caption == caption)
.map(|measure| &measure.value)
}
}
/// The group of the damage to champions, which the player line draws too.
pub(in crate::page) const DEALT: &str = "Dégâts aux champions";
/// What « Score de contrôle » is: Riot gives a bare number, in no unit.
pub(in crate::page) const SCORE_HINT: &str = "Score Riot, sans unité";
/// How a measure is read from a player.
type Read<'a> = &'a dyn Fn(&RecapPlayer) -> Option<u64>;
/// `v`'s share of `of`; 0 when `of` is 0.
fn share(v: u64, of: u64) -> f32 {
if of == 0 { 0. } else { v as f32 / of as f32 }
}
fn measure(caption: &'static str, value: Value) -> Measure {
Measure {
caption,
hint: None,
value,
bar: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::page::matches::shown::{AWAITED, UNAVAILABLE};
fn text(details: &Details, title: &str, caption: &str) -> (String, bool) {
let value = details.get(title, caption).unwrap();
(value.text.to_string(), value.missing)
}
#[test]
fn each_value_is_kept_as_the_source_gives_it() {
let p = RecapPlayer {
damage_to_champions: DamageByType {
total: Some(30_000),
physical: Some(12_000),
magic: Some(17_000),
// 0 is given: shown as 0. The types do not add up to the total: kept so.
true_damage: Some(0),
},
gold_earned: Some(15_000),
gold_spent: Some(0),
total_time_cc_dealt_s: Some(83),
time_ccing_others_s: Some(20),
..RecapPlayer::default()
};
let details = Details::of(&p, UNAVAILABLE, &[&p]);
let at = |title, caption| text(&details, title, caption);
let dealt = "Dégâts aux champions";
assert_eq!(at(dealt, "Total"), ("30\u{202f}000".into(), false));
assert_eq!(at(dealt, "Magiques"), ("17\u{202f}000".into(), false));
assert_eq!(at(dealt, "Bruts"), ("0".into(), false));
assert_eq!(at("Or", "Or gagné"), ("15\u{202f}000 or".into(), false));
assert_eq!(at("Or", "Or dépensé"), ("0 or".into(), false));
assert_eq!(at("Contrôle", "Contrôle infligé").0, "1 min 23 s");
assert_eq!(at("Contrôle", "Score de contrôle").0, "20");
// Absent: the word, never 0.
assert_eq!(at("Dégâts reçus", "Total"), (UNAVAILABLE.into(), true));
assert_eq!(
at("Protection", "Soins aux alliés"),
(UNAVAILABLE.into(), true)
);
}
#[test]
fn the_control_score_says_it_is_riots_number_and_the_mitigation_is_on_oneself() {
let details = Details::of(&RecapPlayer::default(), UNAVAILABLE, &[]);
let control = (details.0.iter().flat_map(|g| &g.measures))
.find(|m| m.caption == "Score de contrôle")
.unwrap();
assert_eq!(control.hint, Some("Score Riot, sans unité"));
assert!(
details
.get("Protection", "Dégâts atténués (sur soi)")
.is_some()
);
let hinted = (details.0.iter().flat_map(|g| &g.measures))
.filter(|m| m.hint.is_some())
.count();
assert_eq!(hinted, 1);
}
#[test]
fn a_provisional_match_waits_for_its_details() {
let details = Details::of(&RecapPlayer::default(), AWAITED, &[]);
assert!(
details
.0
.iter()
.flat_map(|g| &g.measures)
.all(|m| { m.value.missing && m.value.text == AWAITED })
);
}
fn near(bar: Option<f32>, want: f32) {
assert!((bar.unwrap() - want).abs() < 1e-6, "{bar:?} != {want}");
}
fn bar(details: &Details, title: &str, caption: &str) -> Option<f32> {
let group = details.0.iter().find(|g| g.title == title).unwrap();
group
.measures
.iter()
.find(|m| m.caption == caption)
.unwrap()
.bar
}
#[test]
fn damage_bars_are_shares_of_the_sum_of_the_types() {
let p = RecapPlayer {
damage_to_champions: DamageByType {
total: Some(31_000),
physical: Some(12_000),
magic: Some(17_000),
true_damage: Some(1_000),
},
..RecapPlayer::default()
};
let details = Details::of(&p, UNAVAILABLE, &[&p]);
let at = |caption| bar(&details, "Dégâts aux champions", caption);
near(at("Physiques"), 0.4);
near(at("Magiques"), 17. / 30.);
near(at("Bruts"), 1. / 30.);
// Alone in the Match, the total is the best.
near(at("Total"), 1.);
// Nothing given: no bar; types that sum to 0: an empty one.
assert_eq!(bar(&details, "Dégâts reçus", "Physiques"), None);
let zero = DamageByType {
physical: Some(0),
magic: Some(0),
true_damage: Some(0),
..DamageByType::default()
};
// One type absent: no part is drawn, the others would take its share.
let one_absent = DamageByType {
physical: None,
magic: Some(10_000),
true_damage: Some(1_000),
..DamageByType::default()
};
let p = RecapPlayer {
damage_taken: zero,
damage_to_champions: one_absent,
..RecapPlayer::default()
};
let details = Details::of(&p, UNAVAILABLE, &[&p]);
near(bar(&details, "Dégâts reçus", "Physiques"), 0.);
near(bar(&details, "Dégâts reçus", "Bruts"), 0.);
for caption in ["Physiques", "Magiques", "Bruts"] {
assert_eq!(bar(&details, "Dégâts aux champions", caption), None);
}
}
#[test]
fn a_damage_total_is_the_share_of_the_best_total_of_the_match() {
let player = |total| RecapPlayer {
damage_to_champions: DamageByType {
total,
..DamageByType::default()
},
..RecapPlayer::default()
};
let (best, half, absent) = (player(Some(40_000)), player(Some(20_000)), player(None));
let all = [&best, &half, &absent];
let of = |p| bar(&Details::of(p, UNAVAILABLE, &all), DEALT, "Total");
near(of(&best), 1.);
near(of(&half), 0.5);
assert_eq!(of(&absent), None);
}
#[test]
fn a_compared_measure_is_the_share_of_the_best_of_the_match() {
let player = |gold_earned| RecapPlayer {
gold_earned,
..RecapPlayer::default()
};
let (best, other, absent) = (player(Some(15_000)), player(Some(10_000)), player(None));
let all = [&best, &other, &absent];
let of = |p| bar(&Details::of(p, UNAVAILABLE, &all), "Or", "Or gagné");
near(of(&best), 1.);
near(of(&other), 2. / 3.);
assert_eq!(of(&absent), None);
// The best of the Match is 0: an empty bar, not a NaN.
let zero = player(Some(0));
near(
bar(&Details::of(&zero, UNAVAILABLE, &[&zero]), "Or", "Or gagné"),
0.,
);
}
}
+224
View File
@@ -0,0 +1,224 @@
//! The details of the player unfolded, drawn as bars: a row per group, its title then, for the
//! two damage groups, one bar split by type with the total beside it and each type's value in a
//! legend under it, and for the others one bar per measure, full for the best of the Match. The
//! bars are plain boxes, built for the unfolded player only (rule #1).
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::damage::ShownDamage;
use super::damage_view;
use super::details::{DEALT, Details, Group, Measure};
use super::recap::RecapPane;
use super::recap::{PORTRAIT, value};
use crate::theme::gold_ink;
const SPLIT_WIDTH: f32 = 300.;
const SPLIT_HEIGHT: f32 = 8.;
const BAR_WIDTH: f32 = 200.;
const BAR_HEIGHT: f32 = 6.;
const CAPTION_WIDTH: f32 = 170.;
const LINE_WIDTH: f32 = 90.;
/// The measures of a player, a row per group, then the damage seen in the Death Recaps.
pub(super) fn section(
details: &Details,
damage: &ShownDamage,
cx: &Context<RecapPane>,
) -> impl IntoElement {
let theme = cx.theme();
div()
.v_flex()
.gap_2()
.px_2()
.pb_2()
.pl(px(PORTRAIT + 24.))
.debug_selector(|| "recap-details".into())
.children(details.0.iter().enumerate().map(|(group_ix, group)| {
div()
.h_flex()
.flex_wrap()
.items_start()
.gap_x_3()
.gap_y_1()
.child(
div()
.w(px(150.))
.flex_shrink_0()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(group.title),
)
.child(if group.split {
split(group, group_ix, theme).into_any_element()
} else {
bars(group, theme).into_any_element()
})
}))
.child(damage_view::section(damage, cx))
}
/// An empty track, to fill with bars.
fn track(width: f32, height: f32, theme: &Theme) -> Div {
div()
.w(px(width))
.h(px(height))
.flex_shrink_0()
.rounded_full()
.overflow_hidden()
.bg(theme.border)
}
/// Physical, magic and true damage, in the order of a split group's parts.
fn type_colors(theme: &Theme) -> [Hsla; 3] {
[theme.red, theme.blue, theme.foreground]
}
/// A track filled to `length` (0 to 1) by the damage types, each its share of that length.
fn split_bar(parts: &[Measure], length: f32, width: f32, height: f32, theme: &Theme) -> Div {
// The track clips square: the first and last parts drawn round its ends themselves.
let drawn: Vec<_> = (parts.iter().zip(type_colors(theme)))
.filter_map(|(part, color)| part.bar.filter(|&share| share > 0.).map(|s| (s, color)))
.collect();
let last = drawn.len().saturating_sub(1);
track(width, height, theme)
.h_flex()
.children(drawn.into_iter().enumerate().map(|(ix, (share, color))| {
div()
.h_full()
.w(relative(share * length))
.bg(color)
.when(ix == 0, |d| d.rounded_l_full())
.when(ix == last, |d| d.rounded_r_full())
}))
}
/// A player line's damage to champions: a bar as long as its share of the best of the Match,
/// split by type, then the total.
pub(super) fn dealt(details: &Details, theme: &Theme) -> impl IntoElement {
let group = (details.0.iter())
.find(|group| group.title == DEALT)
.expect("the details hold the damage to champions");
let (total, parts) = group
.measures
.split_first()
.expect("a split group has a total");
let length = total.bar.unwrap_or(0.);
let bar = if parts
.iter()
.any(|part| part.bar.is_some_and(|share| share > 0.))
{
split_bar(parts, length, LINE_WIDTH, BAR_HEIGHT, theme)
} else {
// No types to split by (a Provisional Match, or all 0): the length alone, neutral.
track(LINE_WIDTH, BAR_HEIGHT, theme).child(
div()
.h_full()
.w(relative(length))
.rounded_full()
.bg(theme.muted_foreground)
.debug_selector(|| "recap-dealt-plain".into()),
)
};
div()
.h_flex()
.items_center()
.gap_2()
.child(bar)
.child(value(&total.value, theme).text_sm())
}
/// One bar split by type with the total beside it, the types' values in a legend under it.
fn split(group: &Group, group_ix: usize, theme: &Theme) -> impl IntoElement {
let (total, parts) = group
.measures
.split_first()
.expect("a split group has a total");
let colors = type_colors(theme);
let bar = split_bar(parts, 1., SPLIT_WIDTH, SPLIT_HEIGHT, theme);
let legend = div()
.h_flex()
.flex_wrap()
.items_center()
.gap_x_2()
.text_xs()
.children(
parts
.iter()
.zip(colors)
.enumerate()
.flat_map(|(ix, (part, color))| {
[
(ix > 0).then(|| div().text_color(theme.muted_foreground).child("·")),
Some(
div()
.h_flex()
.items_center()
.gap_1()
.child(div().size(px(8.)).flex_shrink_0().rounded_sm().bg(color))
.child(div().text_color(theme.muted_foreground).child(part.caption))
.child(value(&part.value, theme)),
),
]
.into_iter()
.flatten()
}),
);
div()
.v_flex()
.gap_1()
.child(
div()
.h_flex()
.items_center()
.gap_2()
.child(bar.debug_selector(move || format!("recap-split-{group_ix}")))
.child(value(&total.value, theme).text_sm()),
)
.child(legend)
}
/// One line per measure: caption, bar filled to its share of the best of the Match, value.
fn bars(group: &Group, theme: &Theme) -> impl IntoElement {
div()
.v_flex()
.gap_1()
.children(group.measures.iter().map(|measure| line(measure, theme)))
}
fn line(measure: &Measure, theme: &Theme) -> impl IntoElement {
let caption = div()
.w(px(CAPTION_WIDTH))
.flex_shrink_0()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(measure.caption);
let caption = match measure.hint {
// One player is unfolded at a time: the caption names the element.
Some(hint) => caption
.id(hint)
.tooltip(move |window, cx| Tooltip::new(hint).build(window, cx))
.into_any_element(),
None => caption.into_any_element(),
};
div()
.h_flex()
.items_center()
.gap_2()
.child(caption)
.child(
track(BAR_WIDTH, BAR_HEIGHT, theme).when_some(measure.bar, |bar, share| {
bar.child(
div()
.h_full()
.w(relative(share))
.rounded_full()
.bg(gold_ink(theme)),
)
}),
)
.child(value(&measure.value, theme).text_xs())
}
+355
View File
@@ -0,0 +1,355 @@
//! The filters of « Parties »: Season and Format (the selectors and the choice of « Statistiques »,
//! one state for both pages), Placement and champion search (its own). They narrow the Matches
//! already loaded: no query is made, and only the rows kept are written to the list.
use std::ops::Range;
use arena_tracker_core::{ChampionSearch, Season, SeasonScope};
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::component::StyledExt as _;
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::select::Select;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::list::{MatchRow, Outcome};
use super::shown::Champions;
use crate::input_frame::input_frame;
use crate::page::{Page, Tab};
use crate::text::ordinal;
use crate::worker::MatchEntry;
/// What the list says when the filters leave no Match.
pub(super) const NO_RESULT: &str = "Aucune Partie ne correspond aux filtres";
/// « Tous · Top 1 · Victoires ».
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::page) enum PlacementFilter {
All,
/// A Placement of 1.
Top1,
/// The Matches the game itself counts as won.
Wins,
}
/// Each choice with its label and the id the tests click.
const PLACEMENTS: [(&str, &str, PlacementFilter); 3] = [
("matches-placement-all", "Tous", PlacementFilter::All),
("matches-placement-top1", "Top 1", PlacementFilter::Top1),
("matches-placement-wins", "Victoires", PlacementFilter::Wins),
];
impl PlacementFilter {
fn keeps(self, entry: &MatchEntry) -> bool {
match self {
PlacementFilter::All => true,
PlacementFilter::Top1 => entry.placement == 1,
PlacementFilter::Wins => entry.win,
}
}
}
/// The filters of the list that « Statistiques » does not have.
pub(super) struct Filters {
pub(super) placement: PlacementFilter,
pub(super) search: ChampionSearch,
/// The search has a query: the champions are only looked up then.
searching: bool,
pub(super) input: Entity<InputState>,
/// The Season table, oldest first: the periods of the Seasons come from it.
seasons: Vec<Season>,
}
impl Filters {
/// `seasons`: the Season table, oldest first.
pub(super) fn new(seasons: &[Season], window: &mut Window, cx: &mut App) -> Filters {
Filters {
placement: PlacementFilter::All,
search: ChampionSearch::new(""),
searching: false,
input: cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher")),
seasons: seasons.to_vec(),
}
}
/// Back to « Tous » and an empty search, as at launch.
pub(super) fn clear(&mut self, window: &mut Window, cx: &mut App) {
self.placement = PlacementFilter::All;
if self.searching {
self.search = ChampionSearch::new("");
self.searching = false;
self.input
.update(cx, |input, cx| input.set_value("", window, cx));
}
}
/// The period of `season`; none for a Season the table does not know.
fn period(&self, season: &str) -> Range<i64> {
arena_tracker_core::period(&self.seasons, season).unwrap_or(0..0)
}
}
impl Page {
/// The positions, in the entries, of the Matches the filters keep.
fn visible_matches(&self, champions: &Champions) -> Vec<usize> {
let filters = &self.matches.filters;
let period = match &self.season {
SeasonScope::AllSeasons => None,
SeasonScope::Season(name) => Some(filters.period(name)),
};
(self.matches.entries.iter().flatten())
.enumerate()
.filter(|(_, entry)| {
period
.as_ref()
.is_none_or(|p| p.contains(&entry.started_at_ms))
&& self.format.is_none_or(|format| entry.format == format)
&& filters.placement.keeps(entry)
&& (!filters.searching
|| champions.found_by(
&filters.search,
entry.champion_id,
&entry.champion_name,
))
})
.map(|(ix, _)| ix)
.collect()
}
/// Keeps the Matches the filters leave and writes them to the list. The Match chosen stays
/// while it is left; else the first one is chosen, or none when none is. The Match whose end
/// opened the screen is chosen once listed, and nothing before.
pub(super) fn refilter(&mut self, champions: &Champions, cx: &mut Context<Self>) {
let visible = self.visible_matches(champions);
let matches = &mut self.matches;
let entries = matches.entries.as_deref().unwrap_or_default();
let left = |id: &str| visible.iter().any(|&ix| entries[ix].match_id == id);
let first = visible.first().map(|&ix| entries[ix].match_id.clone());
let next = match matches.arriving.take() {
Some(id) if entries.iter().any(|entry| entry.match_id == id) => {
// Hidden by the Season or the Format of « Statistiques »: as an opening by hand.
if left(&id) { Some(id) } else { first }
}
// The list read again will hold it.
Some(id) => {
matches.arriving = Some(id);
None
}
None if matches.selected.as_deref().is_some_and(left) => matches.selected.clone(),
None => first,
};
let rows: Vec<MatchRow> = (visible.iter().map(|&ix| &entries[ix]))
.map(|entry| MatchRow {
match_id: entry.match_id.clone(),
champion: champions.name(entry.champion_id, &entry.champion_name),
portrait: champions.portrait(entry.champion_id),
when: entry.when.clone().into(),
placement: ordinal(entry.placement).into(),
outcome: Outcome::of(entry.placement, entry.win),
provisional: entry.provisional,
})
.collect();
matches.visible = visible;
let choose = next != matches.selected;
if choose {
matches.selected = next;
}
let selected = matches.selected.clone();
matches
.list
.update(cx, |list, cx| list.set_rows(rows, selected.as_deref(), cx));
if choose {
self.request_recap(false);
}
self.dress_banner(cx);
}
/// A filter of this page changed: the list follows while it shows.
fn filtered(&mut self, cx: &mut Context<Self>) {
if self.shown_tab == Tab::Matches || self.tab == Tab::Matches {
let champions = self.champions();
self.refilter(&champions, cx);
}
cx.notify();
}
fn choose_placement(&mut self, placement: PlacementFilter, cx: &mut Context<Self>) {
if self.matches.filters.placement != placement {
self.matches.filters.placement = placement;
self.filtered(cx);
}
}
/// The search field's text changed.
pub(super) fn matches_searched(&mut self, cx: &mut Context<Self>) {
let query = self.matches.filters.input.read(cx).value();
let filters = &mut self.matches.filters;
filters.search = ChampionSearch::new(&query);
filters.searching = !query.is_empty();
self.filtered(cx);
}
/// Above the list: the Season and Format of « Statistiques » (the same selectors), the
/// Placement and the search. Plain elements of the page, a few of them.
pub(super) fn matches_filters(&self, cx: &mut Context<Page>) -> impl IntoElement {
div()
.v_flex()
.gap_2()
.child(
div()
.h_flex()
.gap_2()
.child(
div()
.flex_1()
.min_w_0()
.debug_selector(|| "matches-season".into())
.child(
Select::new(&self.season_select)
.id("season")
.w_full()
.min_w_0(),
),
)
.child(
div()
.flex_1()
.min_w_0()
.debug_selector(|| "matches-format".into())
.child(
Select::new(&self.format_select)
.id("format")
.w_full()
.min_w_0(),
),
),
)
.child(self.placement_control(cx))
.child(
input_frame(
&self.matches.filters.input,
Input::new(&self.matches.filters.input).cleanable(true),
)
.w_full(),
)
}
/// The segmented control « Tous · Top 1 · Victoires ».
fn placement_control(&self, cx: &mut Context<Page>) -> impl IntoElement {
let theme = cx.theme();
let (ring, border, muted, active, active_foreground) = (
theme.ring,
theme.border,
theme.tab_foreground,
theme.tab_active,
theme.tab_active_foreground,
);
let (hover, hover_foreground) = (theme.accent, theme.accent_foreground);
let chosen = self.matches.filters.placement;
div()
.h_flex()
.gap_1()
.p(px(2.))
.rounded_md()
.border_1()
.border_color(border)
.children(PLACEMENTS.map(|(id, label, placement)| {
let current = chosen == placement;
BaseButton::new(id)
.flex_1()
.h_flex()
.justify_center()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
// Always bordered, so the focus ring does not shift the label.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| {
style.border_color(if current { active_foreground } else { ring })
})
.text_color(if current { active_foreground } else { muted })
.when(current, |button| button.bg(active))
.when(!current, |button| {
button.hover(|style| style.bg(hover).text_color(hover_foreground))
})
.accessibility_label(label)
.debug_selector(move || id.into())
.child(label)
.on_click(
cx.listener(move |page, _, _, cx| page.choose_placement(placement, cx)),
)
}))
}
}
/// What the list says when the filters leave no Match, over the empty list.
pub(super) fn no_result(muted: Hsla) -> impl IntoElement {
div()
.absolute()
.top_0()
.left_0()
.right_0()
.p_4()
.text_sm()
.text_color(muted)
.debug_selector(|| "matches-no-result".into())
.child(NO_RESULT)
}
#[cfg(test)]
mod tests {
use super::{MatchEntry, PlacementFilter, Season};
use arena_tracker_core::{Date, Format};
fn entry(placement: u8, win: bool) -> MatchEntry {
MatchEntry {
match_id: "EUW1_1".into(),
champion_id: 1,
champion_name: "Annie".into(),
started_at_ms: 0,
when: String::new(),
placement,
provisional: false,
format: Format::Arena3x6,
win,
}
}
fn season(name: &str, month: u8) -> Season {
Season {
name: name.into(),
start: Date {
year: 2026,
month,
day: 1,
},
official_track: None,
}
}
#[test]
fn top_1_is_a_first_place_and_a_win_is_the_games_own() {
// A 2nd place is a win in Arena 3x6, a 4th is not, and a 1st is both.
let (first, second, fourth) = (entry(1, true), entry(2, true), entry(4, false));
let kept =
|filter: PlacementFilter| [&first, &second, &fourth].map(|entry| filter.keeps(entry));
assert_eq!(kept(PlacementFilter::All), [true; 3]);
assert_eq!(kept(PlacementFilter::Top1), [true, false, false]);
assert_eq!(kept(PlacementFilter::Wins), [true, true, false]);
}
#[test]
fn a_season_runs_to_the_next_ones_start_and_the_last_is_open() {
let (a, b) = (season("A", 1), season("B", 6));
let seasons = [a.clone(), b.clone()];
let first = arena_tracker_core::period(&seasons, "A").unwrap();
assert_eq!(first, a.start.start_ms()..b.start.start_ms());
assert_eq!(
arena_tracker_core::period(&seasons, "B").unwrap().end,
i64::MAX
);
}
}
+86
View File
@@ -0,0 +1,86 @@
//! What the tests read of « Parties ».
use super::{Death, Matches, Recap, ShownRecap};
use crate::card_images::CardImages;
use crate::worker::MatchEntry;
use arena_tracker_core::GameCatalog;
use gpui_kit::*;
impl Matches {
pub(in crate::page) fn entries(&self) -> Option<&[MatchEntry]> {
self.entries.as_deref()
}
pub(in crate::page) fn search_input(&self) -> &Entity<gpui_kit::component::input::InputState> {
&self.filters.input
}
pub(in crate::page) fn recap_images(&self, cx: &App) -> Entity<CardImages> {
let Recap::Ready { pane, .. } = &self.recap else {
panic!("no recap")
};
pane.read(cx).images.clone()
}
/// The Match whose end opened the screen, until it is chosen.
pub(in crate::page) fn arriving(&self) -> Option<&str> {
self.arriving.as_deref()
}
pub(in crate::page) fn recap_generation(&self) -> u64 {
self.recap_generation
}
/// The names and icons the recap is written with.
pub(in crate::page) fn catalog(&self) -> &GameCatalog {
&self.catalog
}
pub(in crate::page) fn generation(&self) -> u64 {
self.generation
}
/// A list or a recap is being read.
pub(in crate::page) fn reading(&self) -> bool {
self.job.running() || self.recap_job.running()
}
pub(in crate::page) fn error(&self) -> Option<&SharedString> {
self.error.as_ref()
}
/// What is known of the Death Recaps of the recap shown.
pub(in crate::page) fn death(&self) -> Option<&Death> {
match &self.recap {
Recap::Ready { death, .. } => Some(death),
_ => None,
}
}
/// The Match whose Death Recap is being asked of Riot.
pub(in crate::page) fn death_fetching(&self) -> Option<&str> {
self.death_fetching.as_deref()
}
/// Whether a Death Recap read runs, and the Match of the one waiting (`true`: asks Riot).
pub(in crate::page) fn death_reads(&self) -> (bool, Option<(&str, bool)>) {
let next =
(self.death_next.as_ref()).map(|(recap, fetch)| (recap.match_id.as_str(), *fetch));
(self.death_running, next)
}
pub(in crate::page) fn unfolded(&self, cx: &App) -> Option<usize> {
match &self.recap {
Recap::Ready { pane, .. } => pane.read(cx).open,
_ => None,
}
}
/// The recap shown, once decoded.
pub(in crate::page) fn shown<'a>(&'a self, cx: &'a App) -> Option<&'a ShownRecap> {
match &self.recap {
Recap::Ready { pane, .. } => Some(&pane.read(cx).shown),
_ => None,
}
}
}
+323
View File
@@ -0,0 +1,323 @@
//! The list of « Parties »: one row per Match, newest first, only the rows in view built. It is
//! its own view, the one part of the screen with a state of its own: the selection, the
//! scrolling and the hover. Choosing a row, with the pointer or the keyboard, tells the page,
//! which opens its Match Recap.
use std::ops::Range;
use std::path::PathBuf;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card_images::{self, CardImages};
use crate::theme::gold_ink;
actions!(match_list, [SelectPrevious, SelectNext, OpenSelected]);
/// The list's key context, where the arrows move the selection and Enter opens it.
const CONTEXT: &str = "MatchList";
const ROW_HEIGHT: f32 = 52.;
const PORTRAIT: f32 = 36.;
pub fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("up", SelectPrevious, Some(CONTEXT)),
KeyBinding::new("down", SelectNext, Some(CONTEXT)),
KeyBinding::new("enter", OpenSelected, Some(CONTEXT)),
]);
}
/// One row, written by the page when the list arrives: nothing is formatted while drawing.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct MatchRow {
pub(in crate::page) match_id: String,
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
pub(in crate::page) when: SharedString,
pub(in crate::page) placement: SharedString,
pub(in crate::page) outcome: Outcome,
pub(in crate::page) provisional: bool,
}
/// The result a row's Placement is drawn in: gold for a top 1, green for a Win, red otherwise.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::page) enum Outcome {
Top1,
Win,
Loss,
}
impl Outcome {
/// The ink of its Placement: the palette's text inks, as the kit's base green is too pale
/// on the light theme.
pub(in crate::page) fn ink(self, theme: &Theme) -> Hsla {
match self {
Outcome::Top1 => gold_ink(theme),
Outcome::Win => theme.success,
Outcome::Loss => theme.danger,
}
}
/// A top 1 is also a Win: it is drawn as a top 1.
pub(in crate::page) fn of(placement: u8, win: bool) -> Outcome {
match (placement, win) {
(1, _) => Outcome::Top1,
(_, true) => Outcome::Win,
_ => Outcome::Loss,
}
}
}
/// A Match was chosen in the list; `close`: by a click or Enter, which closes the list laid
/// over the recap in a narrow window. The arrows only move the selection.
pub(in crate::page) struct MatchChosen {
pub(in crate::page) match_id: String,
pub(in crate::page) close: bool,
}
pub(in crate::page) struct MatchList {
rows: Vec<MatchRow>,
selected: Option<usize>,
scroll: UniformListScrollHandle,
focus: FocusHandle,
/// The portraits of the rows painted only (budget 4). Created at the first render.
images: Option<Entity<CardImages>>,
/// Guards the cache in tests.
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl EventEmitter<MatchChosen> for MatchList {}
impl MatchList {
pub(in crate::page) fn new(cx: &mut Context<Self>) -> MatchList {
MatchList {
rows: Vec::new(),
selected: None,
scroll: UniformListScrollHandle::new(),
focus: cx.focus_handle().tab_stop(true),
images: None,
#[cfg(test)]
renders: 0,
}
}
/// Shows `rows` with the Match `selected`; draws again only when something changed, as a
/// sync lists them again.
pub(in crate::page) fn set_rows(
&mut self,
rows: Vec<MatchRow>,
selected: Option<&str>,
cx: &mut Context<Self>,
) {
let selected_ix = selected.and_then(|id| rows.iter().position(|r| r.match_id == id));
if rows != self.rows || selected_ix != self.selected {
self.rows = rows;
self.selected = selected_ix;
cx.notify();
}
}
/// Back to the top, as at each opening of the screen.
pub(in crate::page) fn scroll_to_top(&mut self) {
self.scroll.scroll_to_item(0, ScrollStrategy::Top);
}
/// The list is not shown any more: its portraits are given back, in memory and in the
/// window's atlas.
pub(in crate::page) fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let released = (self.images.as_ref())
.is_some_and(|images| images.update(cx, |images, cx| images.release(window, cx)));
if released {
// A cached view replays its last paint unless it is drawn again.
cx.notify();
}
}
#[cfg(test)]
pub(in crate::page) fn rows(&self) -> &[MatchRow] {
&self.rows
}
#[cfg(test)]
pub(in crate::page) fn selected(&self) -> Option<&str> {
Some(self.rows.get(self.selected?)?.match_id.as_str())
}
#[cfg(test)]
pub(in crate::page) fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
fn choose(&mut self, ix: usize, close: bool, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(ix) else {
return;
};
let match_id = row.match_id.clone();
self.selected = Some(ix);
self.scroll.scroll_to_item(ix, ScrollStrategy::Nearest);
cx.emit(MatchChosen { match_id, close });
cx.notify();
}
/// The arrows: the row above or below the selection, which stays within the list.
fn step(&mut self, step: isize, cx: &mut Context<Self>) {
let last = self.rows.len().saturating_sub(1);
let target = match self.selected {
Some(ix) => ix.saturating_add_signed(step).min(last),
None => 0,
};
if Some(target) != self.selected {
self.choose(target, false, cx);
}
}
fn row(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let row = &self.rows[ix];
let selected = self.selected == Some(ix);
let selected_bg = if theme.list.active_highlight {
theme.tokens.table_active
} else {
theme.tokens.accent
};
let (muted, gold, hover, border) = (
theme.muted_foreground,
gold_ink(theme),
theme.tokens.table_hover,
theme.table_row_border,
);
let placement_ink = row.outcome.ink(theme);
let portrait = match &row.portrait {
Some(path) => img(path.clone())
.size(px(PORTRAIT))
.rounded_md()
.into_any_element(),
None => div()
.size(px(PORTRAIT))
.rounded_md()
.bg(theme.border)
.into_any_element(),
};
div()
.id(ix)
.debug_selector(move || format!("match-row-{ix}"))
.h_flex()
.w_full()
.h(px(ROW_HEIGHT))
.pl_3()
.pr(Scrollbar::width())
.gap_3()
.items_center()
.relative()
.border_b_1()
.border_color(border)
.map(|tr| {
if selected {
// A gold stroke on the left, as the selected tab's colour.
tr.bg(selected_bg).child(
div()
.absolute()
.left_0()
.top_0()
.bottom_0()
.w(px(3.))
.bg(gold),
)
} else {
tr.hover(|style| style.bg(hover))
}
})
.on_click(cx.listener(move |list, _, window, cx| {
window.focus(&list.focus, cx);
list.choose(ix, true, cx);
}))
.child(portrait)
.child(
div()
.v_flex()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(row.champion.clone()),
)
.child(div().text_xs().text_color(muted).child(row.when.clone())),
)
.child(
div()
.v_flex()
.items_end()
.flex_shrink_0()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.text_color(placement_ink)
.child(row.placement.clone()),
)
.children(
(row.provisional)
.then(|| div().text_xs().text_color(gold).child("Provisoire")),
),
)
.into_any_element()
}
}
impl Render for MatchList {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
let ring = cx.theme().ring;
card_images::provide(div(), images)
.id("match-list")
.debug_selector(|| "match-list".into())
.key_context(CONTEXT)
.track_focus(&self.focus)
.on_action(cx.listener(|list, _: &SelectPrevious, _, cx| list.step(-1, cx)))
.on_action(cx.listener(|list, _: &SelectNext, _, cx| list.step(1, cx)))
.on_action(cx.listener(|list, _: &OpenSelected, _, cx| {
if let Some(ix) = list.selected {
list.choose(ix, true, cx);
}
}))
.relative()
.size_full()
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.child(
uniform_list(
"matches",
self.rows.len(),
cx.processor(|list, range: Range<usize>, _, cx| {
range.map(|ix| list.row(ix, cx)).collect::<Vec<_>>()
}),
)
.size_full()
.track_scroll(&self.scroll),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(Scrollbar::width())
.child(Scrollbar::vertical(&self.scroll)),
)
}
}
+454
View File
@@ -0,0 +1,454 @@
//! The recap of « Parties », drawn as functions of the page's render: the Match Recap of the
//! Match chosen, already written (`ShownRecap`), its teams by Placement and one line per
//! player, the Account's in gold. A click or a key on a line unfolds the details of the player.
use std::path::{Path, PathBuf};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use gpui_kit::base::Button as BaseButton;
use super::bubble::{self, Bubble};
use super::details::DEALT;
use super::details_view;
use super::shown::{Described, ShownPlayer, ShownRecap, ShownTeam, Slot, Value};
use crate::card_images::{self, CardImages};
use crate::page::Page;
pub(in crate::page) struct RecapPane {
pub(super) shown: ShownRecap,
pub(super) open: Option<usize>,
pub(super) page: WeakEntity<Page>,
pub(super) images: Entity<CardImages>,
scroll: ScrollHandle,
pub(super) center_player: bool,
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl RecapPane {
pub(super) fn new(
shown: ShownRecap,
center_player: bool,
cx: &mut Context<Page>,
) -> Entity<Self> {
let page = cx.weak_entity();
let images = CardImages::new(cx);
cx.new(|_| Self {
page,
images,
shown,
open: None,
scroll: ScrollHandle::new(),
center_player,
#[cfg(test)]
renders: 0,
})
}
}
impl Render for RecapPane {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
self.images
.update(cx, |images, cx| images.start_render(window, cx));
let center = std::mem::take(&mut self.center_player).then_some(&self.scroll);
div()
.id("recap-scroll")
.track_scroll(&self.scroll)
.debug_selector(|| "recap-viewport".into())
.size_full()
.overflow_y_scroll()
.child(
card_images::provide(div(), self.images.clone())
.v_flex()
.gap_4()
.pr_2()
.debug_selector(|| "recap".into())
.child(header(&self.shown, cx))
.child(teams(&self.shown, self.open, center, cx)),
)
}
}
use crate::theme::{gold_ink, heading, surface};
pub(super) const PORTRAIT: f32 = 32.;
const HEADER_PORTRAIT: f32 = 48.;
const SLOT: f32 = 24.;
/// The most augments a player takes in a Match: as many slots are drawn.
const AUGMENT_SLOTS: usize = 6;
const ITEM: &str = "recap-item";
const AUGMENT: &str = "recap-augment";
/// What the tests name an item slot of a player, found once painted with its bubble.
pub(in crate::page) fn item_selector(player: usize, index: usize) -> String {
format!("{ITEM}-{player}-{index}")
}
/// What the tests name an augment slot of a player, found once painted with its bubble.
pub(in crate::page) fn augment_selector(player: usize, index: usize) -> String {
format!("{AUGMENT}-{player}-{index}")
}
fn portrait(path: Option<&PathBuf>, size: f32, theme: &Theme) -> AnyElement {
match path {
Some(path) => img(path.clone())
.size(px(size))
.flex_shrink_0()
.rounded_md()
.into_any_element(),
None => div()
.size(px(size))
.flex_shrink_0()
.rounded_md()
.bg(theme.border)
.into_any_element(),
}
}
/// A value, muted when it says its absence.
pub(super) fn value(value: &Value, theme: &Theme) -> Div {
div()
.whitespace_nowrap()
.when(value.missing, |text| {
text.text_color(theme.muted_foreground)
})
.child(value.text.clone())
}
/// A caption over its value.
fn stat(caption: &'static str, shown: &Value, width: f32, theme: &Theme) -> Div {
labelled(caption, value(shown, theme).text_sm(), width, theme)
}
/// A caption over what it names.
fn labelled(caption: &'static str, content: impl IntoElement, width: f32, theme: &Theme) -> Div {
let caption = div()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(caption);
div()
.v_flex()
.w(px(width))
.flex_shrink_0()
.child(caption)
.child(content)
}
/// The Account's champion, when and how the Match was played, and « Provisoire ».
pub(in crate::page) fn header(recap: &ShownRecap, cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.h_flex()
.items_center()
.gap_3()
.child(portrait(recap.portrait.as_ref(), HEADER_PORTRAIT, theme))
.child(
div()
.v_flex()
.min_w_0()
.child(heading(cx).text_2xl().child(recap.champion.clone()))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(recap.details.clone()),
),
)
.children(recap.provisional.then(|| provisional_badge(theme)))
}
/// « Provisoire »: the Match is not published by Riot yet.
pub(in crate::page) fn provisional_badge(theme: &Theme) -> impl IntoElement {
div()
.flex_shrink_0()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(gold_ink(theme))
.rounded(px(6.))
.text_xs()
.text_color(gold_ink(theme))
.debug_selector(|| "recap-provisional".into())
.child("Provisoire")
}
/// The teams by Placement, the Account's highlighted; `open`: the player unfolded.
pub(in crate::page) fn teams(
recap: &ShownRecap,
open: Option<usize>,
center: Option<&ScrollHandle>,
cx: &Context<RecapPane>,
) -> impl IntoElement {
let mut index = 0;
div()
.v_flex()
.gap_3()
.children(recap.teams.iter().map(|shown| {
let first = index;
index += shown.players.len();
team(shown, first, open, center, cx)
}))
}
/// `first`: the index of its first player in the recap, which names their item slots.
fn team(
shown: &ShownTeam,
first: usize,
open: Option<usize>,
center: Option<&ScrollHandle>,
cx: &Context<RecapPane>,
) -> impl IntoElement {
let theme = cx.theme();
div()
.v_flex()
.gap_1()
.child(
value(&shown.placement, theme)
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.when(shown.account && !shown.placement.missing, |text| {
text.text_color(gold_ink(theme))
}),
)
.children((shown.players.iter()).enumerate().map(|(ix, shown)| {
let row = player(shown, first + ix, open == Some(first + ix), cx);
match center.filter(|_| shown.is_account) {
Some(scroll) => center_player_row(row, scroll.clone(), cx.weak_entity()),
None => row,
}
}))
}
/// Center the player's button once its actual position and the viewport are known.
fn center_player_row(row: Div, scroll: ScrollHandle, pane: WeakEntity<RecapPane>) -> Div {
row.on_children_prepainted(move |children, window, cx| {
let Some(line) = children.first() else { return };
let mut offset = scroll.offset();
let target = (offset.y + scroll.bounds().center().y - line.center().y)
.clamp(-scroll.max_offset().y, px(0.));
if (target - offset.y).abs() >= px(0.5) {
offset.y = target;
scroll.set_offset(offset);
let pane = pane.clone();
window.defer(cx, move |_, cx| {
let _ = pane.update(cx, |_, cx| cx.notify());
});
}
})
}
/// One line per player: who, their level, K/D/A and damage to champions, then their items and
/// augments under their name. The line is a button: it unfolds the details, built only then.
fn player(shown: &ShownPlayer, ix: usize, open: bool, cx: &Context<RecapPane>) -> Div {
let theme = cx.theme();
let gold = gold_ink(theme);
let (ring, hover, hover_foreground) = (theme.ring, theme.accent, theme.accent_foreground);
let identity = div()
.v_flex()
.flex_1()
.min_w(px(140.))
.overflow_hidden()
.child(
div()
.text_sm()
.whitespace_nowrap()
.font_weight(FontWeight::SEMIBOLD)
.child(shown.champion.clone()),
)
.child(value(&shown.riot_id, theme).text_xs());
let equipment = div()
.h_flex()
.flex_wrap()
.items_center()
.gap_1()
.pl(px(PORTRAIT + 12.))
.child(items(&shown.items, ix, theme))
.child(augments(&shown.augments, ix, theme));
let line = BaseButton::new(("recap-player", ix))
.h_flex()
.items_center()
.flex_wrap()
.w_full()
.gap_x_3()
.gap_y_1()
.px_2()
.py_1()
.rounded_md()
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label(format!("Détails de {}", shown.champion))
.debug_selector(move || format!("recap-player-{ix}"))
.child(
div()
.v_flex()
.flex_1()
.min_w(px(PORTRAIT + 12. + SLOT * 7. + 3. * 6. + 8.))
.gap_1()
.child(
div()
.h_flex()
.items_center()
.gap_3()
.child(portrait(shown.portrait.as_ref(), PORTRAIT, theme))
.child(identity),
)
.child(equipment),
)
.child(stat("Niveau", &shown.level, 72., theme))
.child(stat("K/D/A", &shown.kda, 120., theme))
.child(
labelled(
DEALT,
details_view::dealt(&shown.details, theme),
// The bar, then « Indisponible » at its widest.
180.,
theme,
)
.debug_selector(move || format!("recap-dealt-{ix}")),
)
.child(
Icon::new(if open {
IconName::ChevronDown
} else {
IconName::ChevronRight
})
.small()
.text_color(theme.muted_foreground),
)
.on_click(cx.listener(move |page, _, _, cx| {
page.open = (page.open != Some(ix)).then_some(ix);
cx.notify();
}));
div()
.v_flex()
.rounded_md()
.border_1()
.map(|card| {
if shown.is_account {
card.border_color(gold)
.bg(gold.opacity(0.08))
.debug_selector(|| "recap-account".into())
} else {
card.border_color(transparent_black())
}
})
.child(line)
.when(open, |card| {
card.child(details_view::section(
&shown.details,
&shown.damage_seen,
cx,
))
})
}
/// What stands for items or augments the source does not give: « Objets : Indisponible ».
fn absent(caption: &'static str, word: &Value, theme: &Theme) -> AnyElement {
div()
.mr_2()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(format!("{caption} : {}", word.text))
.into_any_element()
}
/// `player`: their index in the recap. Each slot that holds an item, or that the source does not
/// give, has a bubble.
fn items(slots: &Result<[Slot; 7], Value>, player: usize, theme: &Theme) -> AnyElement {
let slots = match slots {
Ok(slots) => slots,
Err(word) => return absent("Objets", word, theme),
};
div()
.h_flex()
.gap(px(3.))
.mr_2()
.children(slots.iter().enumerate().map(|(ix, slot)| {
let (div, bubble) = match slot {
Slot::Empty => return slot_frame(theme).into_any_element(),
Slot::Item(item) => (filled_slot(item, theme), Bubble::of(item)),
Slot::Missing(word) => (slot_frame(theme).border_dashed(), Bubble::Word(word)),
};
bubble::Visible {
div: div.debug_selector(move || item_selector(player, ix)),
id: (ITEM, ix),
bubble,
}
.into_any_element()
}))
.into_any_element()
}
/// A square of the line, items' and augments' alike.
fn slot_frame(theme: &Theme) -> Div {
div()
.size(px(SLOT))
.flex()
.items_center()
.justify_center()
.rounded(px(4.))
.border_1()
.border_color(theme.border)
}
/// A slot holding an item or an augment: its icon, the neutral one when the cache lacks it.
fn filled_slot(shown: &Described, theme: &Theme) -> Div {
slot_frame(theme)
.bg(surface(theme))
.child(match &shown.icon {
// The slot's border stays: the icon is a little inside it.
Some(path) => game_icon(path, SLOT - 2.),
None => neutral_icon(theme),
})
}
/// An icon of the game data, from its file on disk.
fn game_icon(path: &Path, size: f32) -> AnyElement {
img(path.to_path_buf())
.size(px(size))
.flex_shrink_0()
.rounded(px(3.))
.into_any_element()
}
/// What stands for an icon the cache does not hold.
fn neutral_icon(theme: &Theme) -> AnyElement {
Icon::new(IconName::Frame)
.xsmall()
.text_color(theme.muted_foreground)
.into_any_element()
}
/// `player`: their index in the recap. Each augment is a slot as the items are, its name in its
/// bubble; the slots the player did not fill stay empty, so the lines read in columns.
fn augments(augments: &Result<Vec<Described>, Value>, player: usize, theme: &Theme) -> AnyElement {
let augments = match augments {
Ok(augments) => augments,
Err(word) => return absent("Améliorations", word, theme),
};
let empty = AUGMENT_SLOTS.saturating_sub(augments.len());
div()
.h_flex()
.gap(px(3.))
.children(augments.iter().enumerate().map(|(ix, augment)| {
bubble::Visible {
div: filled_slot(augment, theme)
.debug_selector(move || augment_selector(player, ix)),
id: (AUGMENT, ix),
bubble: Bubble::of(augment),
}
.into_any_element()
}))
.children((0..empty).map(|_| slot_frame(theme).into_any_element()))
.into_any_element()
}
+242
View File
@@ -0,0 +1,242 @@
//! How « Parties » is laid out: the banner, then the list and the recap side by side, or the
//! list behind a button in a narrow window.
use super::Recap;
use super::filters::no_result;
use crate::page::home::{StatsNotice, notice_line};
use crate::page::{Page, shown};
use crate::text::stored;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
/// Narrower than this, the list hides behind a button and shows over the recap.
const NARROW: f32 = 900.;
const LIST_WIDTH: f32 = 320.;
/// The least height of the list and the recap under the banner.
const MIN_BODY: f32 = 240.;
impl Page {
/// Under the status messages: the Défi's banner, then the list and the recap side by side,
/// the list behind a button in a narrow window. In a low window the banner leaves them less
/// than their least height: the column scrolls then, as the home's does.
pub(in crate::page) fn matches_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let muted = cx.theme().muted_foreground;
let matches = &self.matches;
let body = match (&matches.puuid, &matches.entries) {
(None, _) => notice_line("matches-notice", StatsNotice::NoAccount.label(None), muted),
(_, None) => match &matches.error {
Some(error) => self.matches_error(error, cx),
None => notice_line("matches-notice", "Chargement des Parties…".into(), muted),
},
(_, Some(entries)) if entries.is_empty() => {
notice_line("matches-notice", stored(0).into(), muted)
}
(_, Some(_)) => self.matches_split(window, cx),
};
let error = (matches.entries.is_some())
.then_some(matches.error.as_ref())
.flatten()
.map(|error| self.matches_error(error, cx));
let column = div().id("matches").v_flex().flex_1().min_h_0().gap_3();
let column = match shown("banner") {
true => column.child(self.banner(window, cx)),
false => column,
};
vec![
column
.child(
div()
.v_flex()
.flex_1()
.min_h(px(MIN_BODY))
.gap_3()
.children(error)
.child(body),
)
.overflow_y_scroll()
.into_any_element(),
]
}
fn matches_error(&self, error: &SharedString, cx: &App) -> AnyElement {
div()
.text_sm()
.text_color(cx.theme().danger)
.debug_selector(|| "matches-error".into())
.child(error.clone())
.into_any_element()
}
/// The list (≈ 320 px) and the recap; narrower than `NARROW`, the list opens over the
/// recap from a button. A list closed is not built, and its portraits are given back once.
fn matches_split(&self, window: &mut Window, cx: &mut Context<Page>) -> AnyElement {
let narrow = window.viewport_size().width < px(NARROW);
let open = self.matches.list_open;
let list_shown = !narrow || open;
if !list_shown && self.matches.list_drawn.replace(false) {
let list = self.matches.list.clone();
cx.defer_in(window, move |_, window, cx| {
list.update(cx, |list, cx| list.release_images(window, cx))
});
}
self.matches.list_drawn.set(list_shown);
let list = list_shown.then(|| self.matches_list(cx));
let recap = div().flex_1().min_w_0().h_full().child(self.recap_pane(cx));
if !narrow {
return div()
.h_flex()
.items_start()
.flex_1()
.min_h_0()
.gap_3()
.children(list)
.child(recap)
.into_any_element();
}
div()
.v_flex()
.flex_1()
.min_h_0()
.gap_2()
.child(self.list_toggle(open, cx))
.child(
div()
.relative()
.flex()
.flex_1()
.min_h_0()
.child(recap)
.children(list.map(|list| {
list.absolute()
.top_0()
.left_0()
.bottom_0()
.shadow_lg()
.debug_selector(|| "matches-list-over".into())
})),
)
.into_any_element()
}
/// The filters over the list of the Matches they keep.
fn matches_list(&self, cx: &mut Context<Page>) -> Div {
let theme = cx.theme();
let (background, border, radius, muted) = (
theme.background,
theme.border,
theme.radius,
theme.muted_foreground,
);
let none = self.matches.visible.is_empty();
div()
.v_flex()
.w(px(LIST_WIDTH))
.max_w_full()
.flex_shrink_0()
.h_full()
.gap_2()
.child(self.matches_filters(cx))
.child(
div()
.relative()
.flex_1()
.min_h_0()
.overflow_hidden()
.bg(background)
.border_1()
.border_color(border)
.rounded(radius)
// A cached view: the page drawn again (the veil, the recap arriving) does
// not draw the list.
.child(
(self.matches.list.clone()).cached(StyleRefinement::default().size_full()),
)
.when(none, |area| area.child(no_result(muted))),
)
}
/// « Parties » with a chevron: opens the list over the recap, or closes it.
fn list_toggle(&self, open: bool, cx: &mut Context<Page>) -> impl IntoElement {
let theme = cx.theme();
let (ring, border, hover, hover_foreground) = (
theme.ring,
theme.border,
theme.accent,
theme.accent_foreground,
);
BaseButton::new("matches-list-toggle")
.self_start()
.h_flex()
.items_center()
.gap_1()
.px_3()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.border_1()
.border_color(border)
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label("Parties")
.debug_selector(|| "matches-list-toggle".into())
.child("Parties")
.child(
Icon::new(if open {
IconName::ChevronUp
} else {
IconName::ChevronDown
})
.small(),
)
.on_click(cx.listener(|page, _, _, cx| {
page.matches.list_open = !page.matches.list_open;
cx.notify();
}))
}
/// The recap of the Match chosen, or what stands in its place.
fn recap_pane(&self, cx: &Context<Page>) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
let content: Vec<AnyElement> = match &self.matches.recap {
Recap::None => Vec::new(),
Recap::Loading { .. } => vec![notice_line(
"recap-loading",
"Chargement du récapitulatif…".into(),
muted,
)],
Recap::Missing => vec![notice_line(
"recap-missing",
"Cette Partie n’est plus enregistrée.".into(),
muted,
)],
Recap::Failed(error) => vec![
div()
.text_sm()
.text_color(cx.theme().danger)
.debug_selector(|| "recap-error".into())
.child(error.clone())
.into_any_element(),
],
Recap::Ready { pane, .. } => {
return pane
.clone()
.cached(StyleRefinement::default().size_full())
.into_any_element();
}
};
div()
.v_flex()
.gap_4()
.pr_2()
.debug_selector(|| "recap".into())
.children(content)
.into_any_element()
}
}
+393
View File
@@ -0,0 +1,393 @@
//! What the recap of « Parties » shows, written once when its Match Recap arrives (or the
//! champions' names and portraits do): the page's render only lays it out.
use std::collections::HashMap;
use std::path::PathBuf;
use arena_tracker_core::{
CatalogDisplay, Champion, ChampionSearch, GameCatalog, MatchRecap, RecapPlayer, Statistics,
};
use gpui_kit::SharedString;
use super::damage::{Death, ShownDamage};
use super::details::Details;
use crate::local_time::local_time;
use crate::text::{duration, match_time, ordinal};
/// A value absent from the source: never shown as 0.
pub(in crate::page) const UNAVAILABLE: &str = "Indisponible";
/// The same in a Provisional Match, whose source gives less until Riot publishes it.
pub(in crate::page) const AWAITED: &str = "En attente";
/// A champion of the catalog, as « Parties » needs it.
struct Known {
champion: Champion,
/// The catalog's name, shared with every row that shows it.
name: SharedString,
portrait: Option<PathBuf>,
}
/// The catalog's name and square portrait of each champion, by id.
#[derive(Default)]
pub(in crate::page) struct Champions(HashMap<u32, Known>);
impl Champions {
/// From statistics, whose rows hold every champion of the catalog whatever their scope.
pub(in crate::page) fn of(stats: Option<&Statistics>) -> Champions {
Champions(
(stats.iter().flat_map(|s| s.rows.iter()))
.map(|row| {
let known = Known {
champion: row.champion.clone(),
name: SharedString::from(row.champion.name.clone()),
portrait: row.portrait.clone(),
};
(row.champion.id, known)
})
.collect(),
)
}
/// The catalog's name, else the one the Match gives (Riot's key, such as « MonkeyKing »).
pub(in crate::page) fn name(&self, id: u32, fallback: &str) -> SharedString {
self.0
.get(&id)
.map_or_else(|| fallback.to_string().into(), |known| known.name.clone())
}
pub(in crate::page) fn portrait(&self, id: u32) -> Option<PathBuf> {
self.0.get(&id).and_then(|known| known.portrait.clone())
}
/// Whether the search finds the champion, by the catalog's names and aliases. Without the
/// catalog, the Match's own name is Riot's key, which the aliases are keyed by.
pub(in crate::page) fn found_by(&self, search: &ChampionSearch, id: u32, key: &str) -> bool {
match self.0.get(&id) {
Some(known) => search.matches(&known.champion),
None => search.matches(&Champion {
id,
key: key.into(),
name: key.into(),
}),
}
}
}
/// A value, or the word for its absence, which is drawn muted.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Value {
pub(in crate::page) text: SharedString,
pub(in crate::page) missing: bool,
}
impl Value {
pub(super) fn of<T>(
value: Option<T>,
missing: &'static str,
show: impl FnOnce(T) -> String,
) -> Value {
match value {
Some(value) => Value {
text: show(value).into(),
missing: false,
},
None => Value {
text: missing.into(),
missing: true,
},
}
}
}
/// An item or an augment as the catalog shows it: in a slot or a line of the damage seen.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Described {
/// « Objet n » or « Amélioration n » when the catalog does not know it.
pub(in crate::page) name: SharedString,
/// For its bubble; None: the catalog has none.
pub(in crate::page) description: Option<SharedString>,
/// None shows the neutral icon.
pub(in crate::page) icon: Option<PathBuf>,
}
impl From<CatalogDisplay> for Described {
fn from(shown: CatalogDisplay) -> Described {
Described {
name: shown.name.into(),
description: shown.description.map(Into::into),
icon: shown.icon,
}
}
}
/// One of the seven item slots.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) enum Slot {
/// The source says the slot is empty (item 0).
Empty,
Item(Described),
/// The source does not give this slot: the word for its absence, in its bubble.
Missing(&'static str),
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownPlayer {
pub(in crate::page) is_account: bool,
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
pub(in crate::page) riot_id: Value,
pub(in crate::page) level: Value,
pub(in crate::page) kda: Value,
/// The word for their absence when the source gives no slot at all.
pub(in crate::page) items: Result<[Slot; 7], Value>,
/// Each with its name (« Amélioration n » when unknown); the word for their absence when
/// the source gives no augment field.
pub(in crate::page) augments: Result<Vec<Described>, Value>,
/// What unfolds under their line.
pub(in crate::page) details: Details,
/// The damage seen in the Death Recaps, under their details.
pub(in crate::page) damage_seen: ShownDamage,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownTeam {
/// « 1ᵉʳ », or the word for an absent Placement.
pub(in crate::page) placement: Value,
/// The team of the Account the recap is for.
pub(in crate::page) account: bool,
pub(in crate::page) players: Vec<ShownPlayer>,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownRecap {
/// The Account's champion.
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
/// « 15 nov. 2026 · 18:29 · Arena 3x6 · 31 min 14 s ».
pub(in crate::page) details: SharedString,
pub(in crate::page) provisional: bool,
/// By Placement, best first, as the core ranks them.
pub(in crate::page) teams: Vec<ShownTeam>,
}
impl ShownRecap {
/// `champion`: the Account's, from its row, should the recap not find the Account.
/// `catalog`: the names and icons of the items and augments. `death`: what is known of the
/// Death Recaps of the Match.
pub(in crate::page) fn new(
recap: &MatchRecap,
champion: (u32, &str),
champions: &Champions,
catalog: &GameCatalog,
death: &Death,
) -> ShownRecap {
let missing = if recap.provisional {
AWAITED
} else {
UNAVAILABLE
};
// Every player of the Match: the best of each measure is its full bar.
let all: Vec<&RecapPlayer> = recap.teams.iter().flat_map(|t| &t.players).collect();
let account = all.iter().find(|p| p.is_account).copied();
let (champion_id, fallback) =
account.map_or(champion, |p| (p.champion_id, p.champion_name.as_str()));
let length = recap
.duration_s
.map_or_else(|| format!("Durée : {}", missing.to_lowercase()), duration);
let details = [
match_time(local_time(recap.started_at_ms)),
recap.format.name(),
length,
]
.join(" · ");
ShownRecap {
champion: champions.name(champion_id, fallback),
portrait: champions.portrait(champion_id),
details: details.into(),
provisional: recap.provisional,
teams: (recap.teams.iter())
.map(|team| ShownTeam {
placement: Value::of(team.placement, missing, ordinal),
account: team.players.iter().any(|p| p.is_account),
players: (team.players.iter())
.map(|p| player(p, &all, recap.provisional, death, champions, catalog))
.collect(),
})
.collect(),
}
}
}
fn player(
p: &RecapPlayer,
all: &[&RecapPlayer],
provisional: bool,
death: &Death,
champions: &Champions,
catalog: &GameCatalog,
) -> ShownPlayer {
let missing = if provisional { AWAITED } else { UNAVAILABLE };
let count = |value: Option<u32>| value.map_or_else(|| missing.to_string(), |v| v.to_string());
let kda = [p.kills, p.deaths, p.assists];
let absent = || Value::of(None::<()>, missing, |_| String::new());
let items = (p.items.iter().any(Option::is_some))
.then(|| {
p.items.map(|slot| match slot {
Some(0) => Slot::Empty,
Some(id) => Slot::Item(catalog.item_display(id).into()),
None => Slot::Missing(missing),
})
})
.ok_or_else(absent);
ShownPlayer {
is_account: p.is_account,
champion: champions.name(p.champion_id, &p.champion_name),
portrait: champions.portrait(p.champion_id),
riot_id: Value::of(p.riot_id.clone(), missing, |id| id),
level: Value::of(p.level, missing, |level| level.to_string()),
// Each part says its own absence; all three absent is one word.
kda: Value::of(
kda.iter().any(Option::is_some).then_some(kda),
missing,
|kda| kda.map(count).join(" / "),
),
items,
augments: (p.augments.as_ref())
.map(|augments| {
(augments.iter())
.map(|&id| catalog.augment_display(id).into())
.collect()
})
.ok_or_else(absent),
details: Details::of(p, missing, all),
damage_seen: ShownDamage::of(p, provisional, death, catalog),
}
}
#[cfg(test)]
mod tests {
use super::*;
use arena_tracker_core::{DamageByType, Format, RecapTeam};
fn recap(provisional: bool, players: Vec<RecapPlayer>) -> MatchRecap {
MatchRecap {
match_id: "EUW1_1".into(),
provisional,
format: Format::Arena3x6,
started_at_ms: 1_794_763_752_767,
duration_s: None,
game_version: None,
teams: vec![RecapTeam {
placement: None,
players,
}],
}
}
#[test]
fn an_absent_value_is_unavailable_and_a_zero_stays_zero() {
let given = RecapPlayer {
is_account: true,
champion_id: 39,
champion_name: "Irelia".into(),
kills: Some(0),
deaths: Some(0),
assists: None,
level: Some(0),
items: [Some(0), Some(3157), None, None, None, None, None],
augments: Some(vec![]),
damage_to_champions: DamageByType {
total: Some(0),
..DamageByType::default()
},
..RecapPlayer::default()
};
let shown = ShownRecap::new(
&recap(false, vec![given]),
(1, "x"),
&Champions::default(),
&GameCatalog::default(),
&Death::Loading,
);
let team = &shown.teams[0];
assert_eq!(team.placement.text, UNAVAILABLE);
assert!(team.placement.missing && team.account);
let p = &team.players[0];
assert_eq!(p.riot_id.text, UNAVAILABLE);
assert!(p.riot_id.missing);
assert_eq!((p.level.text.as_ref(), p.level.missing), ("0", false));
assert_eq!(p.kda.text, "0 / 0 / Indisponible");
assert_eq!(
p.details.get("Dégâts aux champions", "Total").unwrap().text,
"0"
);
let slots = p.items.as_ref().unwrap();
assert_eq!(slots[0], Slot::Empty);
let unknown = Slot::Item(Described {
name: "Objet 3157".into(),
description: None,
icon: None,
});
assert_eq!(slots[1], unknown);
assert_eq!(slots[2], Slot::Missing(UNAVAILABLE));
assert_eq!(p.augments, Ok(vec![]));
assert!(shown.details.ends_with("Arena 3x6 · Durée : indisponible"));
assert_eq!(shown.champion, "Irelia");
}
#[test]
fn a_player_without_any_field_is_unavailable_everywhere() {
let bare = RecapPlayer {
champion_id: 39,
champion_name: "Irelia".into(),
..RecapPlayer::default()
};
let shown = ShownRecap::new(
&recap(false, vec![bare]),
(39, "x"),
&Champions::default(),
&GameCatalog::default(),
&Death::Loading,
);
let p = &shown.teams[0].players[0];
for value in [
&p.riot_id,
&p.level,
&p.kda,
p.details.get("Dégâts aux champions", "Total").unwrap(),
] {
assert_eq!((value.text.as_ref(), value.missing), (UNAVAILABLE, true));
}
for absent in [p.items.as_ref().err(), p.augments.as_ref().err()] {
assert_eq!(absent.map(|v| v.text.as_ref()), Some(UNAVAILABLE));
}
}
#[test]
fn a_provisional_match_waits_for_its_values() {
let bare = RecapPlayer::default();
let shown = ShownRecap::new(
&recap(true, vec![bare]),
(39, "x"),
&Champions::default(),
&GameCatalog::default(),
&Death::Loading,
);
assert!(shown.provisional);
assert_eq!(shown.teams[0].players[0].level.text, AWAITED);
let given = RecapPlayer {
items: [Some(3089), None, None, None, None, None, None],
..RecapPlayer::default()
};
let shown = ShownRecap::new(
&recap(true, vec![given]),
(39, "x"),
&Champions::default(),
&GameCatalog::default(),
&Death::Loading,
);
let slots = shown.teams[0].players[0].items.as_ref().unwrap();
assert_eq!(slots[1], Slot::Missing(AWAITED));
assert_eq!(shown.teams[0].placement.text, AWAITED);
}
}
+99
View File
@@ -0,0 +1,99 @@
//! The player unfolded in a recap decoded again (a published or corrected Match): a new
//! Placement may reorder the teams, so the player is found again rather than their place kept.
use arena_tracker_core::{MatchRecap, RecapPlayer};
/// Where the player at `open` in `old` (teams in order) is in `new`: the Account's player, else
/// the one player with the same champion, and the same Riot ID when both give one. `None` when
/// that is not exactly one player: the details fold rather than show someone else's.
pub(super) fn same_player(old: &MatchRecap, open: usize, new: &MatchRecap) -> Option<usize> {
let player = players(old).nth(open)?;
if player.is_account {
return players(new).position(|p| p.is_account);
}
let same = |p: &RecapPlayer| {
!p.is_account
&& p.champion_id == player.champion_id
&& (p.riot_id.is_none() || player.riot_id.is_none() || p.riot_id == player.riot_id)
};
let mut found = players(new).enumerate().filter(|(_, p)| same(p));
let (index, _) = found.next()?;
found.next().is_none().then_some(index)
}
fn players(recap: &MatchRecap) -> impl Iterator<Item = &RecapPlayer> {
recap.teams.iter().flat_map(|team| team.players.iter())
}
#[cfg(test)]
mod tests {
use super::*;
use arena_tracker_core::{Format, RecapTeam};
fn player(champion_id: u32, riot_id: Option<&str>) -> RecapPlayer {
RecapPlayer {
champion_id,
riot_id: riot_id.map(Into::into),
..RecapPlayer::default()
}
}
fn recap(teams: Vec<Vec<RecapPlayer>>) -> MatchRecap {
MatchRecap {
match_id: "EUW1_1".into(),
provisional: false,
format: Format::Arena3x6,
started_at_ms: 0,
duration_s: None,
game_version: None,
teams: (teams.into_iter())
.map(|players| RecapTeam {
placement: None,
players,
})
.collect(),
}
}
#[test]
fn the_player_is_followed_to_their_new_place() {
let old = recap(vec![
vec![player(1, Some("A#EUW")), player(2, Some("B#EUW"))],
vec![player(3, Some("C#EUW")), player(4, Some("D#EUW"))],
]);
// Published: the second team is placed first.
let new = recap(vec![
vec![player(3, Some("C#EUW")), player(4, Some("D#EUW"))],
vec![player(1, Some("A#EUW")), player(2, None)],
]);
assert_eq!(same_player(&old, 0, &new), Some(2));
assert_eq!(same_player(&old, 1, &new), Some(3), "no Riot ID in one");
assert_eq!(same_player(&old, 3, &new), Some(1));
}
#[test]
fn the_account_s_player_is_followed_whatever_its_riot_id() {
let mut alice = player(39, Some("Alice#EUW"));
alice.is_account = true;
let old = recap(vec![vec![player(1, None)], vec![alice.clone()]]);
alice.riot_id = Some("Renamed#EUW".into());
let new = recap(vec![vec![alice], vec![player(1, None)]]);
assert_eq!(same_player(&old, 1, &new), Some(0));
}
#[test]
fn an_uncertain_match_folds_the_details() {
let old = recap(vec![vec![player(1, None), player(2, Some("B#EUW"))]]);
let twice = recap(vec![vec![
player(1, Some("X#EUW")),
player(1, Some("Y#EUW")),
]]);
let other = recap(vec![vec![player(2, Some("Z#EUW"))]]);
assert_eq!(same_player(&old, 0, &twice), None, "two players fit");
assert_eq!(same_player(&old, 1, &other), None, "another Riot ID");
assert_eq!(same_player(&old, 5, &other), None, "no such player");
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The navigation between the screens: the tabs of the top bar (« Défi », « Parties » and,
//! during an Arena champ select, « Sélection », during a Live Match « En partie »), and the veil
//! under which the screen arriving replaces the one leaving. « La phase décide »: entering an
//! Arena champ select shows « Sélection », its end shows « Défi », or « En partie » when it
//! launched the game; the start of a Live Match shows « En partie », its end « Parties » or
//! « Défi » (#129); nothing else moves the player.
use super::{Page, Tab};
use crate::motion::{Fade, FadePhase};
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
impl Page {
/// The tabs as buttons: they take the keyboard focus, and Enter or Space activates them.
/// « Défi » stays lit on « Statistiques », the Challenge's detail page, and takes back to the
/// Challenge from there. « Parties » is right of it, then « Sélection », there only while an
/// Arena champ select runs.
pub(super) fn navigation(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (ring, muted, active, active_foreground, hover, hover_foreground) = (
theme.ring,
theme.tab_foreground,
theme.tab_active,
theme.tab_active_foreground,
theme.accent,
theme.accent_foreground,
);
let champ_select =
(self.in_champ_select()).then_some(("tab-champ-select", "Sélection", Tab::ChampSelect));
let in_game = (self.has_in_game_tab()).then_some(("tab-in-game", "En partie", Tab::InGame));
let tabs = [
("tab-challenge", "Défi", Tab::Challenge),
("tab-matches", "Parties", Tab::Matches),
]
.into_iter()
.chain(champ_select)
.chain(in_game);
div()
.h_flex()
.gap_1()
.flex_shrink_0()
.children(tabs.map(|(id, label, tab)| {
let current = self.lit(tab);
BaseButton::new(id)
.px_3()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
// Always bordered, so the focus ring does not shift the label.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| {
style.border_color(if current { active_foreground } else { ring })
})
.text_color(if current { active_foreground } else { muted })
.when(current, |button| button.bg(active))
.when(!current, |button| {
button.hover(|style| style.bg(hover).text_color(hover_foreground))
})
.accessibility_label(label)
.debug_selector(move || id.into())
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}))
}
/// Whether the top bar lights `tab`: the one chosen, « Défi » on « Statistiques » too.
pub(super) fn lit(&self, tab: Tab) -> bool {
match self.tab {
Tab::Statistics => tab == Tab::Challenge,
chosen => chosen == tab,
}
}
pub(super) fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
// « Sélection » only exists while the champ select runs, « En partie » while the Live
// Match does.
if (tab == Tab::ChampSelect && !self.in_champ_select())
|| (tab == Tab::InGame && !self.has_in_game_tab())
{
return;
}
if self.tab != tab {
self.tab = tab;
// The grids leave under the veil: no card stays lifted over it.
self.lifts.clear();
if !self.may_animate(window, cx) {
// Nothing to see: the end state at once.
self.end_fade(window, cx);
} else {
// From where the veil is: a switch during a transition does not wait for it.
let now = cx.background_executor().now();
let veil = self.veil(cx);
self.fade = Some(if self.shown_tab == tab {
Fade::uncovering(veil, now)
} else {
Fade::covering(veil, now)
});
self.next_fade_frame(window, cx);
}
cx.notify();
}
}
/// Draws the screen of the tab chosen.
fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.shown_tab == self.tab {
return;
}
let left = std::mem::replace(&mut self.shown_tab, self.tab);
// The home grid is no longer under the pointer.
self.release_home(cx);
if left == Tab::ChampSelect {
// The hand is in its place when « Sélection » shows again: its deal does not play
// twice, and no card waits to go down.
self.forget_stage();
}
if left == Tab::Matches {
self.close_matches(window, cx);
}
if self.shown_tab == Tab::Matches {
self.open_matches(cx);
}
// The screen arriving was not kept up to date while hidden, and is prepared only now: a
// switch undone under the veil prepares nothing.
self.refresh_table(cx);
if self.home_cards_stale {
self.prepare_home_cards(cx);
}
self.refresh_home(cx);
if self.shown_tab == Tab::InGame {
self.prepare_in_game(cx);
} else if left == Tab::InGame && !self.in_live_match() {
// What « En partie » showed after its Live Match goes with it.
self.in_game.clear();
}
// The ring and the illustration are the banner's on « Défi », « Parties », « Sélection »
// and « En partie ».
self.dress_banner(cx);
self.release_hidden(window, cx);
}
/// Gives back the images of the screens not shown (rule #1): they load again with their
/// screen.
fn release_hidden(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let shown = self.shown_tab;
if shown != Tab::Challenge {
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
}
if shown != Tab::ChampSelect {
for grid in [&self.anvil_grid, &self.others_grid] {
grid.update(cx, |grid, cx| grid.release_images(window, cx));
}
}
if shown != Tab::Matches {
self.release_matches_images(window, cx);
}
if shown == Tab::Statistics {
// No banner is shown: its illustration goes too.
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
}
if shown != Tab::Statistics {
self.table
.update(cx, |table, cx| table.release_images(window, cx));
}
}
/// Shows the end of the transition, if one runs, at once.
pub(super) fn end_fade(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.fade = None;
self.show_tab(window, cx);
self.play_waiting(window, cx);
cx.notify();
}
/// Asks for the transition's next frame, once.
pub(super) fn next_fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.frame_asked {
self.frame_asked = true;
cx.on_next_frame(window, |page, window, cx| page.fade_frame(window, cx));
}
}
/// One frame of the transition: the screen arriving replaces the one leaving under the full
/// veil, and no frame is asked for once the veil is lifted.
fn fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.frame_asked = false;
let Some(fade) = &self.fade else {
return;
};
let now = cx.background_executor().now();
if fade.finished(now) {
match fade.phase() {
FadePhase::Out => {
// The champ select that ended leaves under the full veil: its end chooses
// « Défi », which comes out of it, as after a switch of tabs.
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.show_tab(window, cx);
self.fade = Some(Fade::uncovering(1., now));
}
FadePhase::In => return self.end_fade(window, cx),
}
}
self.next_fade_frame(window, cx);
cx.notify();
}
}
+33 -30
View File
@@ -1,4 +1,4 @@
use super::{MatchPlayback, Page, Tab, WaitingMatch, home};
use super::{MatchPlayback, Page, Tab, WaitingMatch};
use crate::motion::MatchAnimation;
use arena_tracker_core::FollowedMatch;
use gpui_kit::*;
@@ -12,18 +12,16 @@ impl Page {
let active = self.playback.active() || self.playback.kept_card.is_some();
self.playback = MatchPlayback::default();
if active {
self.banner_art.update(cx, |art, cx| {
art.set_target(self.banner.splash.clone(), cx);
});
self.dress_banner(cx);
self.refresh_home(cx);
}
}
/// The end of a followed Match: it plays once the statistics with it are shown and « Défi »
/// is in front. Of several meanwhile, the strongest plays, on its own champion; the most
/// The end of a followed Match: it plays once the statistics with it are shown and its screen
/// is in front (« Défi », or « Parties » once its end opens its recap there). Of several meanwhile, the strongest plays, on its own champion; the most
/// recent of the strongest. With the Windows « Show animations » setting off, the end state
/// is all there is.
pub(in crate::page) fn queue_match(&mut self, event: FollowedMatch, cx: &mut Context<Self>) {
pub(in crate::page) fn queue_match(&mut self, event: &FollowedMatch, cx: &mut Context<Self>) {
if cx.reduce_motion() {
return;
}
@@ -31,11 +29,7 @@ impl Page {
self.end_match(cx);
}
if self.playback.waiting.waiting().is_none() {
self.playback.previous_banner = Some(if self.in_champ_select() {
home::BannerContent::new(self.home_season.as_ref(), self.home_statistics())
} else {
self.banner.clone()
});
self.playback.previous_banner = Some(self.banner.clone());
}
self.playback.stats_pending = true;
let waiting = WaitingMatch {
@@ -54,21 +48,32 @@ impl Page {
}
}
/// Whether « Défi » is in front of the player. A window merely covered by another cannot
/// be told on Windows (GPUI's `WindowVisibility`): visible then means shown and not
/// minimised.
pub(in crate::page) fn challenge_visible(&self, window: &Window) -> bool {
/// Whether the screen the playback plays on is in front of the player: « Défi », or
/// « Parties » when the end of the Match opened its recap there (#110). A window merely
/// covered by another cannot be told on Windows (GPUI's `WindowVisibility`): visible then
/// means shown and not minimised.
pub(in crate::page) fn playback_visible(&self, window: &Window) -> bool {
let screen = if self.playback.on_matches {
Tab::Matches
} else {
Tab::Challenge
};
window.is_visible()
&& !self.covered
&& self.tab == Tab::Challenge
&& self.shown_tab == Tab::Challenge
&& self.tab == screen
&& self.shown_tab == screen
&& self.fade.is_none()
&& !self.in_champ_select()
}
/// « Défi » may have become visible: the animation waiting, if any, plays.
/// The screen of the playback may have become visible: the animation waiting, if any, plays.
/// On « Parties » it waits for the Match its end opened to be the one chosen, so that the
/// illustration arriving after the comet is its champion's.
pub(in crate::page) fn play_waiting(&mut self, window: &Window, cx: &mut Context<Self>) {
if self.challenge_visible(window)
let chosen = !self.playback.on_matches
|| (self.matches.arriving.is_none() && self.matches.selected.is_some());
if self.playback_visible(window)
&& chosen
&& !cx.reduce_motion()
&& !self.playback.stats_pending
&& let Some(waiting) = self.playback.waiting.shown()
@@ -80,16 +85,14 @@ impl Page {
waiting.end,
cx.background_executor().now(),
);
// Under the comet, the splash of the champion validé before.
let target = (self.playback.previous_banner.as_ref())
.filter(|_| {
self.playback
.animation
.is_some_and(MatchAnimation::has_comet)
})
.unwrap_or(&self.banner)
.splash
.clone();
// Nothing is aimed at while it plays.
self.leave_ring(cx);
// Under the comet, the splash of the champion of the Match before.
let comet = (self.playback.animation).is_some_and(MatchAnimation::has_comet);
let target = match &self.playback.previous_banner {
Some(previous) if comet => previous.splash.clone(),
_ => self.banner_splash(),
};
self.banner_art
.update(cx, |art, cx| art.set_target(target, cx));
if self.playback.animation.is_none() {
+139
View File
@@ -0,0 +1,139 @@
//! The ring under the pointer (#112): it aims at the tick nearest by angle, lights it and has the
//! banner present its champion, over the rest state of the screen shown (`dress_banner`). Nothing
//! is touched until the aimed tick changes (rule #1), and nothing outside the ring.
use std::cell::Cell;
use std::rc::Rc;
use arena_tracker_core::{ChampionRow, Splash};
use gpui_kit::*;
use super::Page;
use super::home::Line;
use crate::text::{ordinal, short_date};
/// The champion aimed at, with what the banner shows for it, prepared when the aim changes.
pub(in crate::page) struct Aimed {
pub(in crate::page) id: u32,
/// Replaces the banner's first line.
pub(in crate::page) line: Line,
pub(in crate::page) splash: Option<Rc<Splash>>,
}
#[derive(Default)]
pub(in crate::page) struct RingHover {
/// Where the ring is, written by its slot at each prepaint (no render, no notification).
bounds: Rc<Cell<Bounds<Pixels>>>,
pub(in crate::page) aimed: Option<Aimed>,
}
/// The champion's line: « X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur
/// Placement 3ᵉ » or « X · jamais joué », from the Season's Challenge figures, all Formats.
fn champion_line(row: &ChampionRow) -> Line {
let challenge = row.challenge.unwrap_or_default();
let detail = if let Some(day) = challenge.completed_on {
let attempts = match row.attempts {
Some(1) => " · du premier coup".to_owned(),
Some(n) => format!(" · {n} Tentatives"),
None => String::new(),
};
format!(" · validé le {}{attempts}", short_date(day))
} else if challenge.matches == 0 {
" · jamais joué".to_owned()
} else {
let n = challenge.matches;
let best = (challenge.best_placement)
.map(|placement| format!(" · meilleur Placement {}", ordinal(placement)))
.unwrap_or_default();
format!(" · {n} {}{best}", if n == 1 { "Partie" } else { "Parties" })
};
Line::new("", &row.champion.name, &detail)
}
impl Page {
/// The ring's slot of the banner, `size` wide: the cached ring, the end of a Match over it,
/// and the pointer's listeners, which are not the ring's (it stays cached).
pub(in crate::page) fn ring_slot(
&self,
size: f32,
now: std::time::Instant,
cx: &mut Context<Page>,
) -> impl IntoElement {
let bounds = self.ring_hover.bounds.clone();
div()
.id("ring-slot")
.relative()
.size(px(size))
.flex_none()
.on_mouse_move(
cx.listener(|page, event: &MouseMoveEvent, _, cx| {
page.aim_ring(event.position, cx)
}),
)
.on_hover(cx.listener(|page, hovered: &bool, _, cx| {
if !*hovered {
page.leave_ring(cx);
}
}))
.child(
canvas(move |at, _, _| bounds.set(at), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.child(
self.ring
.clone()
.cached(StyleRefinement::default().size_full()),
)
.children(
(self.playback.animation)
.map(|a| self.ring.read(cx).match_layer(a, a.elapsed(now), cx)),
)
}
/// The pointer moved over the ring's slot, at `at` in the window: a change of the aimed
/// tick lights it and shows its champion, else nothing is done. Ignored while the end of a
/// Match plays.
pub(in crate::page) fn aim_ring(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
if self.playback.animation.is_some() {
return;
}
let bounds = self.ring_hover.bounds.get();
let id = (self.ring.read(cx)).champion_at(at - bounds.origin, bounds.size);
if id == self.ring_hover.aimed.as_ref().map(|aimed| aimed.id) {
return;
}
self.ring_hover.aimed = id.and_then(|id| self.aimed(id));
self.dress_banner(cx);
cx.notify();
}
/// The pointer left the ring's slot, or the end of a Match starts: the banner is at rest
/// again.
pub(in crate::page) fn leave_ring(&mut self, cx: &mut Context<Self>) {
if self.ring_hover.aimed.take().is_some() {
self.dress_banner(cx);
cx.notify();
}
}
/// New statistics: the champion aimed at, if any, is presented from them.
pub(in crate::page) fn reaim(&mut self) {
let id = self.ring_hover.aimed.as_ref().map(|aimed| aimed.id);
self.ring_hover.aimed = id.and_then(|id| self.aimed(id));
}
fn aimed(&self, id: u32) -> Option<Aimed> {
let row = (self.home_statistics()?.rows.iter()).find(|row| row.champion.id == id)?;
// The champ select keeps its champions' splashes: no new one to allocate for them.
let splash = match self.champ_select_splashes.get(&id) {
Some(splash) => Some(splash.clone()),
None => row.splash.clone().map(Rc::new),
};
Some(Aimed {
id,
line: champion_line(row),
splash,
})
}
}
+27 -20
View File
@@ -1,7 +1,9 @@
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, now_ms,
ALL_FORMATS, ALL_SEASONS, AccountList, Launch, MatchPlayback, Page, SORTS, Tab, home, in_game,
now_ms,
};
use crate::banner_art::BannerArt;
use crate::card_grid::{CardGrid, Paging};
@@ -35,12 +37,13 @@ impl Page {
notice,
following,
champion_sort,
open_recap_at_match_end,
} = launch;
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
let season_table = tracker.seasons();
let seasons: Vec<SharedString> = season_table
.iter()
.rev()
.map(|s| s.name.into())
.map(|s| s.name.clone().into())
.chain([ALL_SEASONS.into()])
.collect();
let current_season = tracker.current_season(now_ms()).map(|s| s.name);
@@ -52,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)];
@@ -85,11 +89,13 @@ impl Page {
let ring = cx.new(|_| Ring::new());
let banner_art = BannerArt::new(cx);
let others_hover = Self::light_and_reveal(&others_grid, cx);
let matches = super::matches::Matches::new(&season_table, window, cx);
let mut subscriptions = Vec::new();
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| {
@@ -137,18 +143,10 @@ 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 Account being updated is following it again.
let following = this
.status
.updating
.as_ref()
.is_some_and(|a| a.puuid == *puuid);
this.pinned = (!following).then(|| puuid.clone());
this.reload(window, cx);
|this, _, event: &SelectEvent<AccountList>, window, cx| {
if let SelectEvent::Confirm(Some(puuid)) = event {
this.account_chosen(puuid, window, cx);
}
},
),
cx.subscribe_in(
@@ -210,8 +208,11 @@ impl Page {
tx,
notice,
champ_select: None,
champ_select_account: None,
champ_select_riot_id: None,
live_match: None,
match_over: None,
in_game: in_game::InGame::default(),
phase_account: None,
phase_riot_id: None,
accounts: Vec::new(),
last_active: None,
pinned: None,
@@ -255,9 +256,11 @@ impl Page {
home_error: None,
home_computed: None,
banner: home::BannerContent::default(),
champ_select_banner: home::BannerContent::default(),
champ_select_splashes: HashMap::new(),
ring,
lit_by: None,
ring_hover: Default::default(),
banner_art,
home_filter: StateFilter::All,
home_search: ChampionSearch::new(""),
@@ -270,6 +273,7 @@ impl Page {
stored: None,
account_select,
account_items: Vec::new(),
friends,
season_select,
format_select,
format_names,
@@ -287,6 +291,9 @@ impl Page {
paging,
champ_select_scrollbar,
others_focus,
matches,
open_recap_at_match_end,
decided_game: None,
others_hover,
_subscriptions: subscriptions,
_listener: listener,
+37 -45
View File
@@ -1,8 +1,9 @@
//! The « Statistiques » tab: the analysis of one Account, Season and Format.
//! The « Statistiques » page, the Challenge's detail: the analysis of one Account, Season and
//! Format.
mod data;
use arena_tracker_core::{ChallengeSummary, Charts, ProgressCheck, StateFilter};
use arena_tracker_core::{ChallengeSummary, Charts, StateFilter};
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
@@ -11,8 +12,9 @@ use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{Page, shown};
use crate::text::{decimal, official_note};
use super::{Page, Tab as Screen, shown};
use crate::input_frame::input_frame;
use crate::text::decimal;
use crate::theme::{heading, surface};
const NO_MATCH: &str = "Aucune Partie";
@@ -36,13 +38,9 @@ fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] {
}
}
fn tile(
label: &'static str,
value: String,
note: Option<String>,
theme: &Theme,
) -> impl IntoElement {
fn tile(label: &'static str, value: String, theme: &Theme) -> impl IntoElement {
div()
.debug_selector(move || format!("tile-{label}"))
.v_flex()
.flex_1()
.gap_1()
@@ -63,44 +61,21 @@ fn tile(
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
.children(note.map(|note| {
div()
.text_xs()
.text_color(theme.muted_foreground)
.child(note)
}))
}
fn challenge_tiles(
c: &ChallengeSummary,
official: Option<&ProgressCheck>,
theme: &Theme,
) -> impl IntoElement {
fn challenge_tiles(c: &ChallengeSummary, theme: &Theme) -> impl IntoElement {
let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2));
// Next to the count whether the app agrees or not; the banner covers the difference.
let note = match official {
Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => {
Some(official_note(*n))
}
_ => None,
};
div()
.h_flex()
.gap_3()
.child(tile(
"Champions validés",
format!("{} / {}", c.completed, c.total),
note,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), None, theme))
.child(tile("Tentatives par champion validé", average, None, theme))
.child(tile(
"Du premier coup",
c.first_tries.to_string(),
None,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), theme))
.child(tile("Tentatives par champion validé", average, theme))
.child(tile("Du premier coup", c.first_tries.to_string(), theme))
}
/// A titled card holding a chart, or `empty` in its place.
@@ -311,6 +286,7 @@ impl Page {
let options = filters(self.in_season());
let selected = options.iter().position(|(_, f)| *f == self.filter);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
let muted = cx.theme().muted_foreground;
let mut content = Vec::new();
// The Season and Format only exist where they are analysed: with the title, under the
// transition's veil, so the header does not change while the screen leaving is visible.
@@ -321,9 +297,23 @@ impl Page {
.items_center()
.justify_between()
.gap_3()
.when(shown("statistics-title"), |row| {
row.child(heading(cx).text_3xl().child("Statistiques"))
})
.child(
// « ‹ Défi » at the top left, then the title.
div()
.h_flex()
.items_center()
.gap_3()
.child(self.tab_link(
"back-to-challenge",
"‹ Défi",
Screen::Challenge,
muted,
cx,
))
.when(shown("statistics-title"), |row| {
row.child(heading(cx).text_3xl().child("Statistiques"))
}),
)
.child(
div()
.h_flex()
@@ -337,7 +327,7 @@ impl Page {
if shown("tiles")
&& let Some(c) = challenge
{
content.push(challenge_tiles(c, self.official(), cx.theme()).into_any_element());
content.push(challenge_tiles(c, cx.theme()).into_any_element());
}
content.push(
self.charts
@@ -366,10 +356,12 @@ impl Page {
})),
)
.child(
Input::new(&self.search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.search_input,
Input::new(&self.search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.)),
)
.into_any_element(),
);
+59 -40
View File
@@ -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::{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,37 +27,45 @@ impl Page {
}
/// Re-reads the Accounts and selects the one shown.
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();
pub(in crate::page) fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let directory = self.tracker.account_directory();
self.accounts.clone_from(&directory.accounts);
self.last_active.clone_from(&directory.last_active);
self.friends.ids.clone_from(&directory.friends);
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
let items: Vec<AccountItem> = self
.accounts
.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 {
// The live champ select's Account may now be in the list: resolve it again.
self.champ_select_riot_id = None;
self.phase_riot_id = None;
}
// During a champ select the selector (disabled) shows the signed-in Account.
let viewed = if self.in_champ_select() {
self.champ_select_account()
if changed {
(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.
self.matches_changed(cx);
}
/// The selector shows the Account of the screen: during a champ select or a Live Match
/// (disabled) the one signed in, else the one viewed.
pub(in crate::page) fn select_shown_account(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
let shown = if self.in_phase() {
self.phase_account()
} else {
self.viewed().map(|a| a.puuid.clone())
};
self.account_select.update(cx, |select, cx| {
if changed {
select.set_items(items, window, cx);
}
if let Some(puuid) = &viewed
if let Some(puuid) = &shown
&& select.selected_value() != Some(puuid)
{
select.set_selected_value(puuid, window, cx);
@@ -74,23 +83,33 @@ impl Page {
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
if self.in_champ_select() {
if computing {
self.stats_generation += 1;
}
// The home is the champ select's: its Challenge is the current Season's, which is
// the Statistics scope for the whole champ select.
self.home_scope = None;
self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name);
self.home_season = self.current_season.clone().map(Into::into);
let puuid = self.champ_select_account()?;
return self.current_season.is_some().then_some(puuid);
}
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
self.filter = StateFilter::All;
}
if self.in_phase() {
if computing {
self.stats_generation += 1;
}
// The home is the phase's, on « Défi » too: its Challenge is the current Season's,
// whatever « Statistiques » analyses.
self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name);
self.home_season = self.current_season.clone().map(Into::into);
let home = self.current_season.clone().map(|season| Scope {
season: SeasonScope::Season(season),
format: None,
});
self.home_scope = home.filter(|home| *home != self.statistics_scope());
let phase = self.phase_account();
if phase != self.shown {
self.filter = StateFilter::All;
self.home_filter = StateFilter::All;
self.shown.clone_from(&phase);
}
let puuid = phase?;
return self.current_season.is_some().then_some(puuid);
}
let previous_season = self.home_season.clone();
self.settle_home_scope();
let viewed = self.viewed().map(|a| a.puuid.clone());
@@ -103,6 +122,8 @@ impl Page {
}
if viewed != self.shown {
// Another Account may not have played the selected Format.
self.filter = StateFilter::All;
self.home_filter = StateFilter::All;
self.shown = viewed.clone();
if self.format.take().is_some() {
self.format_select.update(cx, |select, cx| {
@@ -197,14 +218,10 @@ impl Page {
if !self.hold_grid {
self.reorder();
}
if self.in_champ_select() {
// Neither the charts, the table nor the home grid are shown during a champ select.
self.prepare_banner(cx);
self.prepare_champ_select(cx);
cx.notify();
return;
}
self.prepare_banner(cx);
if self.in_champ_select() {
self.prepare_champ_select(cx);
}
self.prepare_home_cards(cx);
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
@@ -222,6 +239,8 @@ impl Page {
.update(cx, |select, cx| select.set_items(names, window, cx));
}
self.refresh_table(cx);
// The champions' names and portraits of « Parties » come with the statistics.
self.dress_matches(cx);
if self.hold_grid {
// The cards changed in place; their order, which are shown and their count wait for
// the pointer to leave, prepared now.
+27 -1
View File
@@ -1,7 +1,11 @@
mod account;
mod account_deletion;
mod account_selector;
mod banner;
mod banner_fixtures;
mod banner_link;
mod banner_scope;
mod banner_splash;
mod card_sheet;
mod champ_select_browsing;
mod champ_select_capture;
@@ -9,11 +13,33 @@ mod champ_select_fixtures;
mod champ_select_motion;
mod champ_select_others;
mod champ_select_scroll;
mod champ_select_tab;
pub(crate) mod client_fixtures;
pub(crate) mod friends_fixtures;
mod grid;
mod home;
mod in_game;
mod in_game_end;
mod in_game_fixtures;
mod key_fixtures;
mod match_animation;
mod match_end_fixtures;
mod matches;
mod matches_auto_open;
mod matches_banner;
mod matches_bubble;
mod matches_death_recap;
mod matches_details;
mod matches_end_animation;
mod matches_filters;
pub(crate) mod matches_fixtures;
mod matches_game_data;
pub(crate) mod matches_provisional;
mod matches_refresh;
mod navigation;
mod page_fixtures;
pub(crate) mod page_fixtures;
mod portraits;
mod ring_hover;
mod sorting;
mod sorting_fixtures;
mod statistics_tiles;
+10 -7
View File
@@ -37,7 +37,7 @@ async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) {
}
#[gpui::test]
async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pinned_page(
async fn champ_select_uses_the_signed_in_accounts_challenge_and_leaves_the_active_account_shown(
cx: &mut TestAppContext,
) {
use crate::worker::Msg;
@@ -61,8 +61,8 @@ async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pin
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
// The champ select takes the home, about the signed-in Account's current Season.
assert_eq!(p.tab, Tab::Challenge);
// « Sélection » shows, about the signed-in Account's current Season.
assert_eq!(p.tab, Tab::ChampSelect);
assert_eq!(p.displayed().unwrap().puuid, "Alice");
assert_eq!(p.home_season, p.current_season.clone().map(Into::into));
assert!(p.home_season.is_some());
@@ -85,13 +85,16 @@ async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pin
p.apply(Msg::ChampSelect(None), w, cx);
})
});
// The hand leaves « Sélection », then « Défi » shows.
finish_motion(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.viewed().unwrap().puuid, "Bob");
page.read_with(cx, |p, _| {
// The page is back on the active Account, « Tous » shown; the Season is kept.
assert_eq!(p.pinned, None);
assert_eq!(p.viewed().unwrap().puuid, "Alice");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.filter, StateFilter::NeverPlayed);
assert_eq!(p.filter, StateFilter::All);
assert_eq!(p.tab, Tab::Challenge);
assert!(p.table.read(cx).names().is_empty());
});
}
@@ -0,0 +1,23 @@
use super::{matches_fixtures::tracker, page_fixtures::open_page_with_tracker};
use crate::page::Page;
use gpui_kit::{Entity, TestAppContext};
#[gpui::test]
async fn deleting_the_displayed_account_brings_back_the_active_account(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (tracker, _) = tracker();
let (page, mut window): (Entity<Page>, _) = open_page_with_tracker(cx, tracker);
cx.condition(&page, |p, _| p.stats.is_some()).await;
let tracker = page.read_with(&window, |p, _| p.tracker.clone());
window.update(|w, cx| page.update(cx, |p, cx| p.show_account(Some("Bob".into()), w, cx)));
page.read_with(&window, |p, _| assert_eq!(p.viewed().unwrap().puuid, "Bob"));
tracker.delete_account("Bob").unwrap();
window.update(|w, cx| page.update(cx, |p, cx| p.account_deleted("Bob", w, cx)));
page.read_with(&window, |p, _| {
assert_eq!(p.pinned, None);
assert_eq!(p.viewed().unwrap().puuid, "Alice");
});
cx.condition(&page, |p, _| p.account_items.len() == 1).await;
assert_eq!(tracker.accounts().unwrap().len(), 1);
}
@@ -0,0 +1,257 @@
//! The Account selector of the top bar (#115): it chooses the Account of « Défi », « Statistiques »
//! and « Parties », the active one first; the phases and the end of a Match bring the active one
//! back.
use super::matches_auto_open::{before_the_end, game_ends, its_recap, settle_tabs, tabs};
use super::matches_fixtures::{BOB, chosen, listed, recap_ready, sign_in_bob, tracker_in};
use super::page_fixtures::{draw, open_page_with_tracker, season, switch_tab};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, FollowedMatch, Format, MatchEnd, StateFilter};
use gpui_kit::component::select::SelectEvent;
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
use std::sync::{Arc, Mutex};
/// The page on Alice (signed in to the client), Bob stored, in a Season, its statistics there;
/// the name signed in to the client.
async fn on_alice(
cx: &mut TestAppContext,
) -> (Entity<Page>, VisualTestContext, Arc<Mutex<String>>) {
cx.executor().allow_parking();
let (tracker, signed_in) = tracker_in(false, vec![season("Saison", 2020)]);
let (page, window) = open_page_with_tracker(cx, tracker);
cx.condition(&page, |p, _| p.stats.is_some()).await;
(page, window, signed_in)
}
/// The player picks `puuid` in the selector of the top bar.
fn pick(page: &Entity<Page>, cx: &mut VisualTestContext, puuid: &str) {
let select = page.read_with(cx, |p, _| p.account_select.clone());
let puuid = puuid.to_string();
cx.update(|_, cx| select.update(cx, |_, cx| cx.emit(SelectEvent::Confirm(Some(puuid)))));
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())
})
}
fn overline(page: &Entity<Page>, cx: &mut VisualTestContext) -> String {
page.read_with(cx, |p, _| p.banner.season.to_string())
}
fn listed_accounts(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<String> {
page.read_with(cx, |p, _| {
(p.account_items.iter()).map(|a| a.puuid.clone()).collect()
})
}
#[gpui::test]
async fn the_active_account_is_listed_first(cx: &mut TestAppContext) {
let (page, mut window, signed_in) = on_alice(cx).await;
assert_eq!(listed_accounts(&page, &mut window), ["Alice", "Bob"]);
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
// Bob signs in to the client: he is the active one now, and comes first.
sign_in_bob(&page, &signed_in, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert_eq!(listed_accounts(&page, &mut window), ["Bob", "Alice"]);
assert_eq!(selected(&page, &mut window).as_deref(), Some("Bob"));
}
#[gpui::test]
async fn another_account_shows_its_challenge_statistics_and_matches(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
assert_eq!(overline(&page, &mut window), "SAISON");
window.update(|_, cx| {
page.update(cx, |p, _| {
p.home_filter = StateFilter::Completed;
p.filter = StateFilter::NeverPlayed;
})
});
pick(&page, &mut window, "Bob");
page.read_with(&window, |p, _| {
// Nothing computed on the UI thread: Alice's statistics are gone, Bob's on their way.
assert!(p.stats.is_none());
assert_eq!(p.pinned.as_deref(), Some("Bob"));
assert_eq!(
(p.home_filter, p.filter),
(StateFilter::All, StateFilter::All)
);
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
let generation = page.read_with(&window, |p, _| p.stats_generation);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.shown.as_deref(), Some("Bob"));
assert!(p.official().is_none());
// Computed once: the job ended and nothing asked for another.
assert!(!p.stats_job.running());
assert_eq!(p.stats_generation, generation);
});
assert_eq!(overline(&page, &mut window), "Défi de Bob · SAISON");
// « Parties » lists his Matches, and the selector stays enabled there.
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), [BOB]);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(BOB));
assert_eq!(selected(&page, &mut window).as_deref(), Some("Bob"));
// Picking the active Account is following it again.
pick(&page, &mut window, "Alice");
page.read_with(&window, |p, _| assert_eq!(p.pinned, None));
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert_eq!(overline(&page, &mut window), "SAISON");
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window).len(), 3);
}
#[gpui::test]
async fn a_phase_brings_the_active_account_back(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
pick(&page, &mut window, "Bob");
cx.condition(&page, |p, _| p.stats.is_some()).await;
// An Arena champ select starts.
let pick_ = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick_))), w, cx)
})
});
page.read_with(&window, |p, _| {
assert_eq!(p.pinned, None);
assert_eq!(p.displayed().unwrap().puuid, "Alice");
});
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
window.update(|w, cx| page.update(cx, |p, cx| p.apply(Msg::ChampSelect(None), w, cx)));
super::champ_select_fixtures::finish_motion(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
// After it, the active Account is shown.
page.read_with(&window, |p, _| {
assert_eq!(p.viewed().unwrap().puuid, "Alice")
});
assert_eq!(overline(&page, &mut window), "SAISON");
// A Live Match starts.
pick(&page, &mut window, "Bob");
window.update(|w, cx| {
let live = arena_tracker_core::LiveMatch {
riot_id: "Alice#EUW".into(),
game_id: Some(1),
champion_id: Some(39),
};
page.update(cx, |p, cx| p.apply(Msg::LiveMatch(Some(live)), w, cx))
});
page.read_with(&window, |p, _| {
assert_eq!(p.pinned, None);
assert_eq!(p.displayed().unwrap().puuid, "Alice");
});
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
}
/// A follower round reports Alice's Match, as the follower does while Alice is signed in.
fn alice_finishes_a_match(page: &Entity<Page>, cx: &mut VisualTestContext) {
cx.update(|window, cx| {
page.update(cx, |p, cx| {
let matches = vec![FollowedMatch {
puuid: "Alice".into(),
game_id: None,
season: Some("Saison".into()),
format: Format::Arena3x6,
match_id: "EUW1_1".into(),
provisional: false,
champion_id: 1,
started_at_ms: 1,
end: MatchEnd::Mark,
}];
let status = p.status.clone();
p.apply(
Msg::Round {
status,
reload: false,
matches,
game_end: None,
},
window,
cx,
)
})
});
}
#[gpui::test]
async fn the_end_of_a_match_of_the_active_account_does_not_play_for_another(
cx: &mut TestAppContext,
) {
let (page, mut window, _) = on_alice(cx).await;
pick(&page, &mut window, "Bob");
cx.condition(&page, |p, _| p.stats.is_some()).await;
alice_finishes_a_match(&page, &mut window);
page.read_with(&window, |p, _| assert!(!p.playback.active()));
// Shown again, Alice's Match is the one that plays.
pick(&page, &mut window, "Alice");
cx.condition(&page, |p, _| p.stats.is_some()).await;
alice_finishes_a_match(&page, &mut window);
page.read_with(&window, |p, _| assert!(p.playback.active()));
// And leaving her drops it.
pick(&page, &mut window, "Bob");
page.read_with(&window, |p, _| assert!(!p.playback.active()));
}
#[gpui::test]
async fn the_recap_of_the_active_accounts_match_shows_the_active_account(cx: &mut TestAppContext) {
let (page, mut window, client, _) = before_the_end(cx);
window.update(|w, cx| page.update(cx, |p, cx| p.show_account(Some("Bob".into()), w, cx)));
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
page.read_with(&window, |p, _| {
assert_eq!(p.pinned, None);
assert_eq!(p.viewed().unwrap().puuid, "Alice");
});
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
}
#[gpui::test]
async fn with_the_preference_off_the_end_shows_the_active_accounts_challenge(
cx: &mut TestAppContext,
) {
let (page, mut window, client, _) = before_the_end(cx);
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.set_open_recap_at_match_end(false);
p.show_account(Some("Bob".into()), w, cx);
})
});
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
page.read_with(&window, |p, _| {
assert_eq!(p.pinned, None);
assert_eq!(p.viewed().unwrap().puuid, "Alice");
});
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
}
#[gpui::test]
async fn a_new_signed_in_identity_resets_both_filters_even_during_a_phase(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
window.update(|window, cx| {
page.update(cx, |page, cx| {
assert!(page.pinned.is_none());
page.home_filter = StateFilter::NeverPlayed;
page.filter = StateFilter::NeverPlayed;
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
page.apply(Msg::ChampSelect(Some(("Bob#EUW".into(), pick))), window, cx);
assert_eq!(page.displayed().unwrap().puuid, "Bob");
assert_eq!(page.home_filter, StateFilter::All);
assert_eq!(page.filter, StateFilter::All);
})
});
}
+23 -11
View File
@@ -1,6 +1,7 @@
use super::banner_fixtures::{
banner, banner_champion, banner_rows, banner_statistics, bold, draw_loaded, held_splashes,
in_atlas, loaded_splashes, on, ring_renders, ring_ticks, rows_with_splashes, splash,
in_atlas, last_match_of, loaded_splashes, on, ring_renders, ring_ticks, rows_with_splashes,
splash,
};
use super::page_fixtures::{
center, champions, draw, open_page_in_season, show, statistics, switch_tab,
@@ -161,12 +162,12 @@ fn hovering_the_grid_draws_the_ring_only_for_the_tick_that_lights_or_goes_out(
assert_eq!(ring_renders(&page, cx), renders + 2);
// Off the grid, over a button whose hover draws the page: the tick goes out once.
let at = center(cx, "tab-statistics");
let at = center(cx, "statistics-link");
hover(cx, at);
assert_eq!(lit(cx), None);
assert_eq!(ring_renders(&page, cx), renders + 3);
hover(cx, point(px(5.), px(5.)));
let at = center(cx, "tab-statistics");
let at = center(cx, "statistics-link");
hover(cx, at);
assert_eq!(ring_renders(&page, cx), renders + 3);
@@ -225,7 +226,7 @@ fn the_banner_holds_two_splashes_at_most_and_gives_back_the_one_replaced(cx: &mu
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
draw_loaded(cx);
assert!(cx.debug_bounds("banner-art").is_some());
@@ -241,7 +242,7 @@ fn the_banner_holds_two_splashes_at_most_and_gives_back_the_one_replaced(cx: &mu
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![1, 2], None),
banner_statistics(rows_with_splashes(dir.path()), vec![1, 2], last_match_of(2)),
);
draw(cx);
assert_eq!(
@@ -282,16 +283,20 @@ fn a_banner_without_splash_has_no_illustration(cx: &mut TestAppContext) {
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx).len(), 1);
// The last Completed champion's splash is not downloaded yet: no illustration, and the
// The last Match's champion's splash is not downloaded yet: no illustration, and the
// one shown before is given back.
let mut rows = rows_with_splashes(dir.path());
rows[0].splash = None;
show(&page, cx, banner_statistics(rows, vec![2, 1], None));
show(
&page,
cx,
banner_statistics(rows, vec![2, 1], last_match_of(1)),
);
draw(cx);
assert!(cx.debug_bounds("banner").is_some());
assert!(cx.debug_bounds("banner-title").is_some());
@@ -309,7 +314,7 @@ fn in_a_narrow_window_the_ring_goes_above_the_text_and_the_splash_covers_the_ban
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
draw(cx);
let bounds = |cx: &mut VisualTestContext| {
@@ -371,7 +376,10 @@ fn a_splash_asked_for_while_another_decodes_waits_for_it(cx: &mut TestAppContext
let mut rows = rows_with_splashes(dir.path());
rows[2] = banner_champion(4, "Garen", 2, Some(on(11, 21)), 900);
rows[2].splash = Some(splash(dir.path(), "Garen"));
let last = |order: Vec<u32>| banner_statistics(rows.clone(), order, None);
let last = |order: Vec<u32>| {
let last_match = last_match_of(order[order.len() - 1]);
banner_statistics(rows.clone(), order, last_match)
};
show(&page, cx, last(vec![2, 1]));
draw_loaded(cx);
let ahri = loaded_splashes(&page, cx);
@@ -405,7 +413,11 @@ fn opening_another_screen_gives_back_the_splash_and_the_portraits(cx: &mut TestA
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
row.card_portrait = Some(path);
}
show(&page, cx, banner_statistics(rows, vec![2, 1], None));
show(
&page,
cx,
banner_statistics(rows, vec![2, 1], last_match_of(1)),
);
draw_loaded(cx);
let images = page.read_with(cx, |p, cx| p.home_grid.read(cx).images().cloned().unwrap());
let portraits = images.read_with(cx, |images, _| images.loaded());
+13 -3
View File
@@ -4,8 +4,8 @@ use crate::champion_table::tests::row;
use crate::page::Page;
use crate::ring::Tick;
use arena_tracker_core::{
Champion, ChampionChallenge, ChampionRow, ChampionState, Date, LastMatch, Splash, SplashFocus,
Statistics,
Champion, ChampionChallenge, ChampionRow, ChampionState, Date, LastMatch, MatchOutcome, Splash,
SplashFocus, Statistics,
};
use gpui_kit::{Entity, VisualTestContext};
use std::path::Path;
@@ -72,11 +72,21 @@ pub(super) fn banner_statistics(
stats
}
/// The Season's last Match, one that did nothing to the Challenge: the banner's illustration is
/// its champion's splash.
pub(super) fn last_match_of(champion_id: u32) -> Option<LastMatch> {
Some(LastMatch {
champion_id,
placement: 4,
outcome: MatchOutcome::AfterCompletion,
})
}
pub(super) fn banner(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> crate::page::home::BannerContent {
page.read_with(cx, |page, _| page.banner.clone())
page.read_with(cx, |page, _| page.shown_banner().clone())
}
pub(super) fn bold(line: &crate::page::home::Line) -> &str {
+82
View File
@@ -0,0 +1,82 @@
use super::page_fixtures::{
champions, draw, open_page, open_page_with_tracker, season, show, statistics,
};
use arena_tracker_core::{RiotApi, Tracker};
use gpui_kit::{Bounds, Pixels, TestAppContext, VisualTestContext, px, size};
use std::path::Path;
fn bounds(cx: &mut VisualTestContext, id: &'static str) -> Bounds<Pixels> {
cx.debug_bounds(id).unwrap()
}
/// The icon sits in the banner's bottom-right corner, inside its padding (16 to 36 px a side,
/// 24 px under it), and covers none of the text.
fn assert_in_the_corner(cx: &mut VisualTestContext) {
let (link, banner) = (bounds(cx, "statistics-link"), bounds(cx, "banner"));
let right = banner.right() - link.right();
assert!(right >= px(15.) && right <= px(37.), "{link:?} {banner:?}");
assert!(
(banner.bottom() - link.bottom() - px(24.)).abs() < px(1.),
"{link:?} {banner:?}"
);
// A button of the icon's size, not a line of text.
assert!(
link.size.width < px(40.) && link.size.height < px(40.),
"{link:?}"
);
for id in ["banner-season", "no-season", "banner-title"] {
if let Some(text) = cx.debug_bounds(id) {
assert!(!link.intersects(&text), "{id} {text:?} {link:?}");
}
}
}
#[gpui::test]
fn the_icon_is_in_the_banners_bottom_right_corner_not_on_the_seasons_line(cx: &mut TestAppContext) {
let (page, cx) = super::page_fixtures::open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
assert_in_the_corner(cx);
// The Season's line keeps the height of its text, the link no longer sits on it.
let (link, season) = (bounds(cx, "statistics-link"), bounds(cx, "banner-season"));
assert!(season.size.height < px(20.), "{season:?}");
assert!(link.top() > season.bottom(), "{link:?} {season:?}");
}
#[gpui::test]
fn without_a_season_the_icon_is_in_the_corner_too(cx: &mut TestAppContext) {
let (_page, cx) = open_page(cx);
let cx = &mut { cx };
draw(cx);
assert!(cx.debug_bounds("no-season").is_some());
assert_in_the_corner(cx);
}
#[gpui::test]
fn in_a_narrow_window_the_icon_stays_in_the_corner_with_a_long_season(cx: &mut TestAppContext) {
let name =
"Saison très longue qui prend toute la largeur de la bannière étroite et plus encore";
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season(name, 2020)]);
let (page, cx) = open_page_with_tracker(cx, tracker);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
cx.simulate_resize(size(px(480.), px(800.)));
draw(cx);
assert_in_the_corner(cx);
}
#[gpui::test]
fn in_a_narrow_window_the_icon_is_in_the_corner_with_a_short_season(cx: &mut TestAppContext) {
let (page, cx) = super::page_fixtures::open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
cx.simulate_resize(size(px(480.), px(800.)));
draw(cx);
assert_in_the_corner(cx);
}
+4 -4
View File
@@ -1,6 +1,6 @@
use super::banner_fixtures::{
banner, banner_statistics, draw_loaded, held_splashes, in_atlas, loaded_splashes, ring_ticks,
rows_with_splashes, splash,
banner, banner_statistics, draw_loaded, held_splashes, in_atlas, last_match_of,
loaded_splashes, ring_ticks, rows_with_splashes, splash,
};
use super::champ_select_fixtures::{
ANVIL_CARDS, activate, click_others, frames, joueur_tracker, others_open, page_in_champ_select,
@@ -24,7 +24,7 @@ async fn the_banner_forgets_the_previous_scope_while_the_champ_select_loads(
show(
&page,
&mut window,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
assert_eq!(
banner(&page, &mut window).title.text.as_ref(),
@@ -53,7 +53,7 @@ fn scrolling_the_home_moves_the_ring_as_it_is_and_gives_back_a_splash_out_of_vie
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
cx.simulate_resize(size(px(600.), px(340.)));
draw_loaded(cx);
@@ -0,0 +1,32 @@
use super::banner_fixtures::{banner, banner_statistics, last_match_of, rows_with_splashes};
use super::page_fixtures::{draw, open_page_in_season, show};
use crate::card_images::tests::TestDir;
use gpui_kit::{TestAppContext, VisualTestContext};
// The illustration is the last Match's champion's (the « Dernière Partie » line's, whatever its
// Format), not the last champion validé's; none without a Match in the Season.
#[gpui::test]
fn the_illustration_is_the_champion_of_the_last_match(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-last-match");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let splash_name = |cx: &mut VisualTestContext| {
banner(&page, cx)
.splash
.map(|s| s.path.file_name().unwrap().to_string_lossy().into_owned())
};
// Ahri was validé last, but Brand was played since.
let stats = |last| banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last);
show(&page, cx, stats(last_match_of(1)));
assert_eq!(splash_name(cx).as_deref(), Some("Ahri.50.30.jpg"));
show(&page, cx, stats(last_match_of(2)));
assert_eq!(splash_name(cx).as_deref(), Some("Brand.50.30.jpg"));
// The last Match's champion has no splash: none, whatever the others'.
show(&page, cx, stats(last_match_of(4)));
assert_eq!(splash_name(cx), None);
// No Match in the Season: no illustration, though champions were validés.
show(&page, cx, stats(None));
assert_eq!(splash_name(cx), None);
draw(cx);
assert!(cx.debug_bounds("banner-art").is_none());
}
@@ -221,4 +221,5 @@ fn no_champ_select_changes_nothing(cx: &mut TestAppContext) {
});
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("tab-champ-select").is_none());
}
@@ -4,7 +4,7 @@ use super::champ_select_fixtures::{
joueur_tracker_with, leave, page_in_champ_select, places, read_champ_select, reasons, send,
with_bans_and_ally,
};
use super::page_fixtures::{center, draw, open_page, open_page_with_tracker, show, switch_tab};
use super::page_fixtures::{center, draw, open_page, open_page_with_tracker, show};
use crate::card::{ASPECT, Reason};
use crate::card_images::tests::TestDir;
@@ -208,7 +208,9 @@ async fn the_arena_capture_fills_the_anvil_row_in_the_homes_order(cx: &mut TestA
}
#[gpui::test]
async fn the_champ_select_takes_the_home_and_gives_it_back_as_it_was(cx: &mut TestAppContext) {
async fn the_champ_select_takes_the_window_and_gives_the_home_back_as_it_was(
cx: &mut TestAppContext,
) {
use arena_tracker_core::SeasonScope;
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
@@ -237,28 +239,31 @@ async fn the_champ_select_takes_the_home_and_gives_it_back_as_it_was(cx: &mut Te
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
// The Challenge of the signed-in Account in the current Season, whatever the
// Statistics tab shows.
assert_eq!(p.tab, Tab::Challenge);
// « Sélection », from « Statistiques »: the Challenge of the signed-in Account in the
// current Season, whatever « Statistiques » analyses.
assert_eq!(p.tab, Tab::ChampSelect);
assert_eq!(p.shown_tab, Tab::ChampSelect);
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.displayed().unwrap().puuid, "Joueur");
assert_eq!(p.home_season.as_deref(), Some("Saison"));
assert_eq!(p.banner.season.as_ref(), "SAISON · 1 / 9 validés");
assert_eq!(p.banner.title.text.as_ref(), "Sélection des champions");
assert!(p.stats.as_ref().unwrap().challenge.is_some());
assert_eq!(
p.champ_select_banner.season.as_ref(),
"SAISON · 1 / 9 validés"
);
assert_eq!(
p.champ_select_banner.title.text.as_ref(),
"Sélection des champions"
);
assert!(p.home_statistics().unwrap().challenge.is_some());
});
// The row is there; the grid, its filters and its search are not.
// The row is there; the grid, its filters and its search are on « Défi ».
assert!(window.debug_bounds("anvil-row").is_some());
assert!(window.debug_bounds("card-233").is_some());
assert!(window.debug_bounds("home-tools").is_none());
assert!(window.debug_bounds("card-103").is_none());
// « Statistiques » is out of reach during the champ select.
let statistics = center(&mut window, "tab-statistics");
window.simulate_click(statistics, Modifiers::none());
switch_tab(&page, &mut window, Tab::Statistics);
assert_eq!(page.read_with(&window, |p, _| p.tab), Tab::Challenge);
// Its banner is about the champ select only: no link to « Statistiques ».
assert!(window.debug_bounds("statistics-link").is_none());
// Bans and ally picks are the champ select's.
send(&page, &mut window, &with_bans_and_ally(&[16, 233], 233));
@@ -407,13 +407,13 @@ async fn the_entry_waits_for_the_window_and_the_page_to_be_in_front(cx: &mut Tes
start_leaving(&page, cx);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
// Behind « Paramètres »; and from « Statistiques », « Défi » first.
// Behind « Paramètres »; and from « Statistiques », « Sélection » at once.
cx.simulate_visibility_change(WindowVisibility::Visible);
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| page.update(cx, |page, cx| page.hidden(window, cx)));
send(&page, cx, &frames()[0]);
assert!(!entry(cx));
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::ChampSelect);
cx.update(|window, cx| page.update(cx, |page, cx| page.uncovered(window, cx)));
assert!(entry(cx));
finish_motion(&page, cx);
@@ -465,7 +465,9 @@ async fn a_grid_no_longer_shown_asks_for_no_frame(cx: &mut TestAppContext) {
(p.lifts.lifted(hand, now).count(), p.lifts.veil(hand, now))
});
assert_eq!(lifting, (0, 0.));
// The home's card now under the still pointer rises in its turn, then nothing moves.
// The home's card now under the still pointer rises in its turn, and its banner's splash
// fades in, then nothing moves.
settle(cx);
settle(cx);
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
@@ -0,0 +1,217 @@
//! « Sélection », the tab of the champ select's phase (#108): it appears and shows when an
//! Arena champ select starts, lets the player look at « Défi » and come back, and goes when the
//! champ select ends. Only entering a new phase moves the player.
use super::champ_select_fixtures::{
ANVIL_A_TO_Z, anvil_cards, below, finish_motion, frames, joueur_tracker, page_in_champ_select,
reasons, send, start_leaving, with_bans_and_ally,
};
use super::page_fixtures::{
assert_at_rest, center, draw, frame_after, open_page_with_tracker, shown_tab, start_switch,
switch_tab, veil,
};
use crate::card::Reason;
use crate::page::{Page, Tab};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
fn tab(page: &Entity<Page>, cx: &mut VisualTestContext) -> Tab {
page.read_with(cx, |page, _| page.tab)
}
/// Clicks the element `id`, and lets the transition it starts end.
fn click(page: &Entity<Page>, cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_click(at, Modifiers::none());
finish_motion(page, cx);
draw(cx);
}
fn ring_anvil(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<Vec<u32>> {
page.read_with(cx, |p, cx| p.ring.read(cx).anvil().map(<[u32]>::to_vec))
}
#[gpui::test]
async fn entering_a_champ_select_adds_the_selection_tab_and_shows_it(app: &mut TestAppContext) {
app.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(app, joueur_tracker());
let cx = &mut window;
draw(cx);
assert!(cx.debug_bounds("tab-champ-select").is_none());
send(&page, cx, &frames()[0]);
app.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let cx = &mut window;
// At once, right of « Défi », with its entry: the band of light, then the hand dealt.
assert_eq!(tab(&page, cx), Tab::ChampSelect);
assert_eq!(shown_tab(&page, cx), Tab::ChampSelect);
assert!(page.read_with(cx, |p, _| p.fade.is_none() && p.entry.is_some()));
let challenge = cx.debug_bounds("tab-challenge").unwrap();
let selection = cx.debug_bounds("tab-champ-select").unwrap();
assert!(selection.origin.x > challenge.origin.x);
assert!(cx.debug_bounds("sweep").is_some());
assert!(cx.debug_bounds("anvil-row").is_some());
assert!(cx.debug_bounds("home-tools").is_none());
finish_motion(&page, cx);
assert_at_rest(cx);
}
#[gpui::test]
async fn entering_a_champ_select_from_statistics_shows_the_selection(app: &mut TestAppContext) {
app.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(app, joueur_tracker());
app.condition(&page, |p, _| p.stats.is_some()).await;
switch_tab(&page, &mut window, Tab::Statistics);
send(&page, &mut window, &frames()[0]);
app.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let cx = &mut window;
assert_eq!(tab(&page, cx), Tab::ChampSelect);
assert_eq!(shown_tab(&page, cx), Tab::ChampSelect);
assert!(page.read_with(cx, |p, _| p.fade.is_none() && p.entry.is_some()));
assert!(cx.debug_bounds("back-to-challenge").is_none());
assert!(cx.debug_bounds("anvil-row").is_some());
}
// « Défi » shows the home as usual during the champ select, and « Statistiques » stays reachable
// from it; back on « Sélection », the hand is in its place, not dealt again.
#[gpui::test]
async fn the_challenge_and_the_selection_take_turns_without_dealing_again(
app: &mut TestAppContext,
) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
let generation = page.read_with(cx, |p, _| p.stats_generation);
assert!(ring_anvil(&page, cx).is_some());
click(&page, cx, "tab-challenge");
assert_eq!(tab(&page, cx), Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert!(cx.debug_bounds("home-tools").is_some());
assert!(cx.debug_bounds("card-103").is_some());
assert!(cx.debug_bounds("anvil-row").is_none());
assert!(cx.debug_bounds("tab-champ-select").is_some());
// The home's banner: its count and its ring, no tick dimmed.
let title = page.read_with(cx, |p, _| p.shown_banner().title.text.clone());
assert_eq!(title.as_ref(), "1 / 9 champions validés");
assert_eq!(ring_anvil(&page, cx), None);
click(&page, cx, "statistics-link");
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert!(cx.debug_bounds("tab-champ-select").is_some());
click(&page, cx, "tab-champ-select");
assert_eq!(tab(&page, cx), Tab::ChampSelect);
assert_eq!(shown_tab(&page, cx), Tab::ChampSelect);
assert!(cx.debug_bounds("anvil-row").is_some());
assert!(page.read_with(cx, |p, _| p.entry.is_none() && !p.entry_waiting));
for id in ANVIL_A_TO_Z {
assert_eq!(below(cx, id), None, "{id} is dealt again");
}
assert!(ring_anvil(&page, cx).is_some());
let title = page.read_with(cx, |p, _| p.shown_banner().title.text.clone());
assert_eq!(title.as_ref(), "Sélection des champions");
// Nothing was computed again for the switches.
assert_eq!(page.read_with(cx, |p, _| p.stats_generation), generation);
assert_at_rest(cx);
}
#[gpui::test]
async fn bans_and_picks_on_another_tab_do_not_bring_the_selection_back(app: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
switch_tab(&page, cx, Tab::Challenge);
send(&page, cx, &with_bans_and_ally(&[16, 233], 233));
draw(cx);
assert_eq!(tab(&page, cx), Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert!(page.read_with(cx, |p, _| p.fade.is_none() && p.taken.is_empty()));
// The hand follows them all the same, and shows them once back, in its place.
let cards = anvil_cards(&page, cx);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
switch_tab(&page, cx, Tab::Statistics);
send(&page, cx, &with_bans_and_ally(&[16], 233));
draw(cx);
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
switch_tab(&page, cx, Tab::ChampSelect);
draw(cx);
assert!(page.read_with(cx, |p, _| p.taken.is_empty()));
assert_eq!(below(cx, 233), None);
assert_at_rest(cx);
}
// The end of the champ select on « Sélection »: the hand leaves as before, then « Défi » comes
// out of the veil, and the tab is gone.
#[gpui::test]
async fn the_selection_tab_goes_after_the_hand_leaves(app: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
start_leaving(&page, cx);
draw(cx);
assert!(page.read_with(cx, |p, _| p.leave.is_some()));
assert_eq!(shown_tab(&page, cx), Tab::ChampSelect);
assert!(cx.debug_bounds("anvil-row").is_some());
finish_motion(&page, cx);
assert_eq!(tab(&page, cx), Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
app.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let cx = &mut window;
assert!(cx.debug_bounds("tab-champ-select").is_none());
assert!(cx.debug_bounds("home-tools").is_some());
assert_eq!(ring_anvil(&page, cx), None);
assert_at_rest(cx);
}
// Elsewhere nothing of the champ select is drawn: it merely ends, and « Défi » shows.
#[gpui::test]
async fn the_selection_tab_goes_at_once_from_another_tab(app: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
switch_tab(&page, cx, Tab::Challenge);
start_leaving(&page, cx);
draw(cx);
page.read_with(cx, |p, _| {
assert!(!p.in_champ_select());
assert!(p.leave.is_none() && p.fade.is_none());
assert_eq!((p.tab, p.shown_tab), (Tab::Challenge, Tab::Challenge));
});
assert!(cx.debug_bounds("tab-champ-select").is_none());
// From « Statistiques », « Défi » comes as after any switch.
send(&page, cx, &frames()[0]);
finish_motion(&page, cx);
switch_tab(&page, cx, Tab::Statistics);
start_leaving(&page, cx);
assert_eq!(tab(&page, cx), Tab::Challenge);
assert!(page.read_with(cx, |p, _| p.leave.is_none() && p.fade.is_some()));
finish_motion(&page, cx);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert!(cx.debug_bounds("tab-champ-select").is_none());
}
// The champ select ends while « Sélection » goes under the veil for « Défi »: its hand still
// leaves, and the veil holds where it is meanwhile.
#[gpui::test]
async fn an_end_during_a_switch_lets_the_hand_leave_under_the_veil_as_it_is(
app: &mut TestAppContext,
) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
start_switch(&page, cx, Tab::Challenge);
frame_after(cx, 60);
let before = veil(&page, cx);
assert!(before > 0. && before < 1., "{before}");
start_leaving(&page, cx);
assert!(page.read_with(cx, |p, _| p.leave.is_some()));
assert_eq!(veil(&page, cx), before);
finish_motion(&page, cx);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
}
@@ -0,0 +1,60 @@
//! The game client the page tests drive: who is signed in, its gameflow, and the end-of-game
//! block it holds until a follower round takes it.
use arena_tracker_core::{
ChampSelect, ClientError, ClientEvent, EndOfGameBlock, GameClientSource, Gameflow,
};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// Shared with the tracker it is given to: the test changes it as the client would.
#[derive(Clone, Default)]
pub(crate) struct FakeClient {
/// The game name signed in, tag line « EUW »; empty while the client is closed.
pub(crate) name: Arc<Mutex<String>>,
pub(super) flow: Arc<Mutex<Gameflow>>,
pub(crate) block: Arc<Mutex<Option<EndOfGameBlock>>>,
}
impl FakeClient {
/// `name` signed in, in the client's lobby.
pub(crate) fn new(name: &str) -> FakeClient {
FakeClient {
name: Arc::new(Mutex::new(name.into())),
..FakeClient::default()
}
}
}
impl GameClientSource for FakeClient {
fn signed_in(&self) -> Result<(String, String), ClientError> {
let name = self.name.lock().unwrap().clone();
if name.is_empty() {
return Err(ClientError::Absent);
}
Ok((name, "EUW".into()))
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
if self.name.lock().unwrap().is_empty() {
return Err(ClientError::Absent);
}
Ok(self.flow.lock().unwrap().clone())
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
fn take_end_of_game_block(&self) -> Option<EndOfGameBlock> {
self.block.lock().unwrap().take()
}
}
@@ -0,0 +1,128 @@
//! 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(in crate::page) const CARL: [&str; 3] =
["EUW1_9100000003", "EUW1_9100000002", "EUW1_9100000001"];
/// Carl's Matches are fetched while it is open.
pub(in crate::page) struct Gate {
open: Mutex<bool>,
changed: Condvar,
}
impl Gate {
pub(in crate::page) 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(in crate::page) struct Handles {
pub(in crate::page) gate: Arc<Gate>,
/// The Matches of Carl fetched, in order.
pub(in crate::page) fetched: Arc<Mutex<Vec<String>>>,
/// Carl has played a third Match.
pub(in crate::page) third: Arc<AtomicBool>,
/// The key is gone: Riot answers for no Riot ID.
pub(in crate::page) 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(in crate::page) 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)
}
+5 -2
View File
@@ -1,3 +1,4 @@
use super::banner_fixtures::ring_renders;
use super::page_fixtures::{
center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show,
statistics, switch_tab,
@@ -193,16 +194,18 @@ fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext)
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(renders > 0);
let ring = ring_renders(&page, cx);
// A navigation button's hover style redraws the window.
// A navigation button's hover style redraws the window (the icon from where no tick is lit).
for _ in 0..2 {
let button = center(cx, "tab-statistics");
let button = center(cx, "statistics-link");
cx.simulate_mouse_move(button, None, Modifiers::none());
draw(cx);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
assert_eq!(ring_renders(&page, cx), ring);
// The count does move when the grid changes.
grid.update(cx, |_, cx| cx.notify());
+26
View File
@@ -165,6 +165,32 @@ fn the_counter_keeps_its_total_while_a_search_and_a_filter_reduce_the_list(
assert_eq!(counter(cx), "1 / 4 champions validés");
}
#[gpui::test]
fn a_click_in_the_padding_of_the_search_field_gives_it_the_keyboard(cx: &mut TestAppContext) {
use gpui_kit::{Modifiers, point, px};
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 3, champions(3)));
draw(cx);
let input = page.read_with(cx, |p, _| p.home_search_input.clone());
let field = cx.debug_bounds("home-search").unwrap();
let text = |cx: &mut VisualTestContext| input.read_with(cx, |i, _| i.value().to_string());
// Just inside the left border, above the text line: nothing but the frame is there.
cx.simulate_click(
point(field.left() + px(2.), field.top() + px(2.)),
Modifiers::none(),
);
cx.simulate_input("an");
assert_eq!(text(cx), "an");
// The text line still takes its own click, and the field keeps working.
cx.update(|window, cx| window.blur(cx));
cx.simulate_click(field.center(), Modifiers::none());
cx.simulate_input("x");
assert_eq!(text(cx), "anx");
}
#[gpui::test]
fn the_home_follows_the_season_of_the_statistics_but_not_their_format(cx: &mut TestAppContext) {
cx.executor().allow_parking();
+429
View File
@@ -0,0 +1,429 @@
//! « En partie » (#109): the tab of the Live Match's phase, read from the simulated client as
//! the follower reads it. It shows when the game starts, from the champ select or when the
//! client is met in a game, and holds the champion played and its stake in the Challenge.
use super::champ_select_fixtures::{finish_motion, frames, start_leaving};
use super::in_game_fixtures::{
GAME, in_game_ready, joueur_in_champ_select, joueur_in_game, joueur_in_lobby, tell,
};
use super::matches_auto_open::tabs;
use super::page_fixtures::{draw, switch_tab};
use crate::card::sheet_lines;
use crate::page::home::IDENTIFYING;
use crate::page::{Page, Tab};
use crate::text::short_date;
use arena_tracker_core::{GamePhase, LiveMatch};
use gpui_kit::{Entity, TestAppContext, VisualTestContext, WindowVisibility};
fn banner_text(page: &Entity<Page>, cx: &mut VisualTestContext) -> (String, String, String) {
page.read_with(cx, |p, _| {
let banner = p.shown_banner();
(
banner.season.to_string(),
banner.title.text.to_string(),
banner.detail.text.to_string(),
)
})
}
fn lit(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<u32> {
page.read_with(cx, |p, cx| p.ring.read(cx).lit())
}
/// The game starts at the end of the champ select: the follower tells the Live Match, then the
/// champ select's end. The hand leaves as usual, then « En partie » comes out of the veil in
/// place of « Défi », and « Sélection » is gone.
#[gpui::test]
async fn a_game_launched_from_the_champ_select_shows_en_partie(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, cx);
// Still the champ select's: its end decides.
assert_eq!(tabs(&page, cx), (Tab::ChampSelect, Tab::ChampSelect));
assert_eq!(started.get(), 1);
draw(cx);
assert!(cx.debug_bounds("tab-in-game").is_none());
let generation = page.read_with(cx, |p, _| p.stats_generation);
start_leaving(&page, cx);
assert!(page.read_with(cx, |p, _| p.leave.is_some()));
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
// The same Account in the same Season: nothing is computed again.
page.read_with(cx, |p, _| {
assert_eq!(p.stats_generation, generation);
assert!(p.stats.is_some());
});
in_game_ready(&page, app).await;
draw(&mut window);
let cx = &mut window;
assert!(cx.debug_bounds("tab-champ-select").is_none());
let parties = cx.debug_bounds("tab-matches").unwrap();
let in_game = cx.debug_bounds("tab-in-game").unwrap();
assert!(in_game.origin.x > parties.origin.x);
// Briar, played once, not validated: the banner says what a top 1 would bring.
assert_eq!(
banner_text(&page, cx),
(
"SAISON · 1 / 9 validés".into(),
"Briar".into(),
"Un top 1 validerait Briar : 2 / 9".into()
)
);
assert_eq!(lit(&page, cx), Some(233));
// The banner of a phase has no link to « Statistiques ».
assert!(cx.debug_bounds("statistics-link").is_none());
assert!(cx.debug_bounds("in-game-sheet").is_some());
assert!(cx.debug_bounds("in-game-recent").is_some());
assert_eq!(started.get(), 1);
}
/// The game's session names no champion: the one the champ select picked stands in.
#[gpui::test]
async fn the_champion_picked_stands_in_for_one_the_game_does_not_name(app: &mut TestAppContext) {
// The last frame: Soraka locked in.
let (page, mut window, mut client, _) = joueur_in_champ_select(app, &frames()[4]).await;
let cx = &mut window;
client.set(GamePhase::InGame, true, None);
client.read(&page, cx);
start_leaving(&page, cx);
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
in_game_ready(&page, app).await;
let cx = &mut window;
assert_eq!(banner_text(&page, cx).1, "Soraka");
assert_eq!(lit(&page, cx), Some(16));
}
/// The app starts while the client plays: its first read shows « En partie ».
#[gpui::test]
async fn the_app_started_during_a_game_shows_en_partie(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_game(app, 233).await;
let cx = &mut window;
assert_eq!(tabs(&page, cx), (Tab::Challenge, Tab::Challenge));
client.read(&page, cx);
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
assert_eq!(started.get(), 1);
in_game_ready(&page, app).await;
assert_eq!(banner_text(&page, &mut window).1, "Briar");
}
/// The app meets the client in a game: « En partie » shows at once from wherever the player
/// was, the window never activated, and the page says a Live Match started (« Paramètres »
/// gives way and a minimised window opens again, `main`).
#[gpui::test]
async fn a_client_met_in_a_game_shows_en_partie_without_the_focus(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_lobby(app).await;
let cx = &mut window;
switch_tab(&page, cx, Tab::Statistics);
cx.deactivate_window();
cx.simulate_visibility_change(WindowVisibility::Hidden);
client.set(GamePhase::InGame, true, Some(16));
client.read(&page, cx);
// Hidden, the switch is at once, without the veil.
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
assert!(page.read_with(cx, |p, _| p.fade.is_none()));
assert_eq!(started.get(), 1);
cx.update(|window, cx| {
assert_eq!(cx.active_window(), None);
assert!(!window.is_window_active());
assert_eq!(window.focused(cx), None);
});
in_game_ready(&page, app).await;
let cx = &mut window;
// Soraka is validated: the banner gives the day.
let day = page.read_with(cx, |p, _| {
let stats = p.home_statistics().unwrap();
let row = stats.rows.iter().find(|row| row.champion.id == 16).unwrap();
row.challenge.unwrap().completed_on.unwrap()
});
let (_, title, detail) = banner_text(&page, cx);
assert_eq!(title, "Soraka");
assert_eq!(detail, format!("Soraka validé le {}", short_date(day)));
assert_eq!(lit(&page, cx), Some(16));
}
/// The sheet is the card's, and the champion's latest Matches of the Season are listed with
/// their date, Placement and Format; without one, the first Match is announced.
#[gpui::test]
async fn en_partie_holds_the_sheet_and_the_latest_matches(app: &mut TestAppContext) {
let (page, mut window, mut client, _) = joueur_in_lobby(app).await;
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, &mut window);
// « En partie » is prepared once it shows, out of the veil.
finish_motion(&page, &mut window);
in_game_ready(&page, app).await;
let cx = &mut window;
draw(cx);
page.read_with(cx, |p, _| {
let stats = p.home_statistics().unwrap();
let row = stats
.rows
.iter()
.find(|row| row.champion.id == 233)
.unwrap();
assert_eq!(p.in_game.sheet(), sheet_lines(row).as_slice());
let recent = p.in_game.recent_lines().unwrap();
assert_eq!(recent.len(), 1);
let (_, placement, format, provisional) = &recent[0];
assert_eq!(
(placement.as_str(), format.as_str(), *provisional),
("4ᵉ", "Arena 3x6", false)
);
});
assert!(cx.debug_bounds("in-game-sheet-Parties").is_some());
assert!(cx.debug_bounds("in-game-recent-0").is_some());
assert!(cx.debug_bounds("in-game-first-match").is_none());
// The stored Matches changed, as many as before (a Provisional Match Riot published): the
// list is read again, and stays shown until it comes.
let (shown, requests) =
page.read_with(cx, |p, _| (p.in_game.recent_lines(), p.in_game.requests()));
stored_matches_change(&page, cx);
assert_eq!(page.read_with(cx, |p, _| p.in_game.recent_lines()), shown);
app.condition(&page, |p, _| {
p.in_game.requests() == requests + 1 && p.in_game.recent_read()
})
.await;
let cx = &mut window;
// Another game, with Ahri, never played this Season.
client.lobby();
client.read(&page, cx);
client.set(GamePhase::InGame, true, Some(103));
client.read(&page, cx);
finish_motion(&page, cx);
in_game_ready(&page, app).await;
let cx = &mut window;
draw(cx);
assert_eq!(
page.read_with(cx, |p, _| p.in_game.recent_lines()),
Some(Vec::new())
);
assert!(cx.debug_bounds("in-game-first-match").is_some());
assert!(cx.debug_bounds("in-game-recent-0").is_none());
}
/// Until the client says the champion (Bravery draws it), the banner has no illustration and
/// says it is being identified; its champion then fills the screen.
#[gpui::test]
async fn the_champion_is_identified_when_the_client_says_it(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_lobby(app).await;
client.set(GamePhase::InGame, true, None);
client.read(&page, &mut window);
app.condition(&page, |p, _| p.stats.is_some()).await;
finish_motion(&page, &mut window);
draw(&mut window);
let cx = &mut window;
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
let (season, title, detail) = banner_text(&page, cx);
assert_eq!((title.as_str(), detail.as_str()), (IDENTIFYING, ""));
assert_eq!(season, "SAISON · 1 / 9 validés");
page.read_with(cx, |p, cx| {
assert!(p.in_game.banner.splash.is_none());
assert_eq!(p.banner_art.read(cx).target, None);
});
assert_eq!(lit(&page, cx), None);
assert!(cx.debug_bounds("in-game-sheet").is_none());
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, cx);
in_game_ready(&page, app).await;
draw(&mut window);
let cx = &mut window;
assert_eq!(banner_text(&page, cx).1, "Briar");
assert_eq!(lit(&page, cx), Some(233));
assert!(cx.debug_bounds("in-game-sheet").is_some());
// The same Live Match: it did not start again.
assert_eq!(started.get(), 1);
}
/// A follower round that stored or replaced Matches.
fn stored_matches_change(page: &Entity<Page>, cx: &mut VisualTestContext) {
cx.update(|window, cx| {
page.update(cx, |p, cx| {
let status = p.status.clone();
p.apply(
crate::worker::Msg::Round {
status,
reload: true,
matches: Vec::new(),
game_end: None,
},
window,
cx,
)
})
});
}
/// A game outside Arena makes nothing appear.
#[gpui::test]
async fn a_game_outside_arena_shows_nothing(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_lobby(app).await;
let cx = &mut window;
for phase in [GamePhase::ChampSelect, GamePhase::InGame, GamePhase::Ended] {
client.set(phase, false, Some(233));
client.read(&page, cx);
}
draw(cx);
assert_eq!(tabs(&page, cx), (Tab::Challenge, Tab::Challenge));
assert!(cx.debug_bounds("tab-in-game").is_none());
assert!(page.read_with(cx, |p, _| p.live_match.is_none()));
assert_eq!(started.get(), 0);
}
/// During the Live Match « Défi » and « Statistiques » stay reachable, on the signed-in
/// Account's current Challenge, and « En partie » shows again as it was, with nothing computed
/// again; only a new phase moves the player.
#[gpui::test]
async fn the_challenge_and_en_partie_take_turns(app: &mut TestAppContext) {
let (page, mut window, mut client, _) = joueur_in_lobby(app).await;
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, &mut window);
// « En partie » is prepared once it shows, out of the veil.
finish_motion(&page, &mut window);
in_game_ready(&page, app).await;
let cx = &mut window;
let generation = page.read_with(cx, |p, _| (p.stats_generation, p.in_game.recent_lines()));
switch_tab(&page, cx, Tab::Challenge);
draw(cx);
assert!(cx.debug_bounds("home-tools").is_some());
assert!(cx.debug_bounds("tab-in-game").is_some());
assert_eq!(banner_text(&page, cx).1, "1 / 9 champions validés");
// Only a card under the pointer lights a tick there.
assert_eq!(lit(&page, cx), None);
// The client's events change nothing shown.
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::Challenge, Tab::Challenge));
switch_tab(&page, cx, Tab::InGame);
draw(cx);
assert_eq!(banner_text(&page, cx).1, "Briar");
assert_eq!(lit(&page, cx), Some(233));
let again = page.read_with(cx, |p, _| (p.stats_generation, p.in_game.recent_lines()));
assert_eq!(again, generation);
// Hidden, « En partie » is not prepared (rule #1): the Matches stored meanwhile are read
// when it shows again, once.
switch_tab(&page, cx, Tab::Challenge);
let requests = page.read_with(cx, |p, _| p.in_game.requests());
let stats = page.read_with(cx, |p, _| p.stats_generation);
stored_matches_change(&page, cx);
app.condition(&page, |p, _| {
p.stats_generation > stats && p.stats.is_some()
})
.await;
let cx = &mut window;
assert_eq!(page.read_with(cx, |p, _| p.in_game.requests()), requests);
switch_tab(&page, cx, Tab::InGame);
switch_tab(&page, cx, Tab::Challenge);
switch_tab(&page, cx, Tab::InGame);
assert_eq!(
page.read_with(cx, |p, _| p.in_game.requests()),
requests + 1
);
}
/// The end of the game without its end-of-game block: « En partie » stays on the end-of-game
/// screen, then the lobby removes it and shows the Challenge, from wherever the player is.
#[gpui::test]
async fn the_lobby_after_a_game_without_a_block_shows_the_challenge(app: &mut TestAppContext) {
let (page, mut window, mut client, _) = joueur_in_lobby(app).await;
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, &mut window);
// « En partie » is prepared once it shows, out of the veil.
finish_motion(&page, &mut window);
in_game_ready(&page, app).await;
let cx = &mut window;
client.set(GamePhase::Ended, true, Some(233));
client.read(&page, cx);
// The follower's round tells the game's end: the lobby or the block decides.
cx.update(|window, cx| {
page.update(cx, |p, cx| {
let status = p.status.clone();
p.apply(
crate::worker::Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end: Some(arena_tracker_core::GameEnd {
game_id: Some(GAME),
}),
},
window,
cx,
)
})
});
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
switch_tab(&page, cx, Tab::Statistics);
let requests = page.read_with(cx, |p, _| p.in_game.requests());
client.lobby();
client.read(&page, cx);
assert_eq!(page.read_with(cx, |p, _| p.tab), Tab::Challenge);
finish_motion(&page, cx);
app.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let cx = &mut window;
assert_eq!(tabs(&page, cx), (Tab::Challenge, Tab::Challenge));
assert!(cx.debug_bounds("tab-in-game").is_none());
assert_eq!(lit(&page, cx), None);
// What it showed went with the screen; the count of its requests stays, so that a late
// answer is not taken for the next game's.
page.read_with(cx, |p, _| {
assert!(p.in_game.sheet().is_empty());
assert_eq!(p.in_game.requests(), requests);
});
}
/// The client closed during the game, then opened again on it (« Reconnect »): the game had not
/// ended, and its lobby shows the Challenge again, from wherever the player is.
#[gpui::test]
async fn a_game_reconnected_to_ends_at_its_lobby(app: &mut TestAppContext) {
let (page, mut window, mut client, started) = joueur_in_lobby(app).await;
let cx = &mut window;
client.set(GamePhase::InGame, true, Some(233));
client.read(&page, cx);
finish_motion(&page, cx);
client.sign_in("");
client.read(&page, cx);
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::Challenge, Tab::Challenge));
client.sign_in("Joueur");
client.read(&page, cx);
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
assert_eq!(started.get(), 2);
switch_tab(&page, cx, Tab::Statistics);
client.lobby();
client.read(&page, cx);
assert_eq!(page.read_with(cx, |p, _| p.tab), Tab::Challenge);
}
/// A Live Match told while the window shows the page starts with the veil of the tabs.
#[gpui::test]
async fn a_live_match_comes_out_of_the_veil_when_the_window_shows(app: &mut TestAppContext) {
let (page, mut window, _, _) = joueur_in_lobby(app).await;
let cx = &mut window;
let live = LiveMatch {
riot_id: "Joueur#EUW".into(),
game_id: Some(GAME),
champion_id: Some(233),
};
tell(&page, cx, Some(live));
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::Challenge));
assert!(page.read_with(cx, |p, _| p.fade.is_some()));
finish_motion(&page, cx);
assert_eq!(tabs(&page, cx), (Tab::InGame, Tab::InGame));
}
+116
View File
@@ -0,0 +1,116 @@
//! The end of the Live Match with its end-of-game block (#109, #129): the block makes the game a
//! Match, « En partie » goes, and the block decides what shows; the rest of the game's end
//! moves nothing. The Live Match is read from Alice's simulated client.
use super::client_fixtures::FakeClient;
use super::in_game_fixtures::Client;
use super::matches_auto_open::{
before_the_end, game_ends, its_recap, left_alone, settle_tabs, tabs,
};
use super::matches_fixtures::chosen;
use super::matches_provisional::{GAME, MATCH};
use super::page_fixtures::draw;
use crate::page::{Page, Tab};
use arena_tracker_core::GamePhase;
use gpui_kit::{Entity, VisualTestContext};
/// Alice plays the game whose block her client will hold, her champion not said yet (Bravery),
/// then the game ends and her client shows its end-of-game screen.
fn alice_plays(page: &Entity<Page>, fake: &FakeClient, cx: &mut VisualTestContext) -> Client {
let mut client = Client::new(fake.clone(), GAME);
client.set(GamePhase::InGame, true, None);
client.read(page, cx);
settle_tabs(page, cx);
assert_eq!(tabs(page, cx), (Tab::InGame, Tab::InGame));
client.set(GamePhase::Ended, true, None);
client.read(page, cx);
client
}
#[gpui::test]
async fn the_block_of_the_live_match_opens_its_recap_in_place_of_en_partie(
cx: &mut gpui_kit::TestAppContext,
) {
let (page, mut window, fake, opened) = before_the_end(cx);
let mut client = alice_plays(&page, &fake, &mut window);
game_ends(&page, &fake, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(opened.get(), 1);
its_recap(&page, cx).await;
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
draw(&mut window);
assert!(window.debug_bounds("tab-in-game").is_none());
// The client stays on the game's end-of-game screen, where it says Alice's champion at last,
// then goes back to its lobby: the tab does not come back, and nothing moves the player.
client.set(GamePhase::Ended, true, Some(39));
client.read(&page, &mut window);
client.lobby();
client.read(&page, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert!(window.debug_bounds("tab-in-game").is_none());
assert_eq!(opened.get(), 1);
left_alone(&mut window, true);
}
#[gpui::test]
async fn with_the_preference_off_the_block_of_the_live_match_shows_the_challenge(
cx: &mut gpui_kit::TestAppContext,
) {
let (page, mut window, fake, opened) = before_the_end(cx);
page.update(&mut window, |page, _| {
page.set_open_recap_at_match_end(false)
});
let mut client = alice_plays(&page, &fake, &mut window);
game_ends(&page, &fake, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
client.lobby();
client.read(&page, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
draw(&mut window);
assert!(window.debug_bounds("tab-in-game").is_none());
}
/// A block that makes the game a Match but that the end of a Match does not open (another
/// Account's): « Défi » shows rather than a tab the top bar no longer has.
#[gpui::test]
async fn a_block_that_opens_nothing_leaves_en_partie_for_the_challenge(
cx: &mut gpui_kit::TestAppContext,
) {
let (page, mut window, fake, opened) = before_the_end(cx);
alice_plays(&page, &fake, &mut window);
let theirs = arena_tracker_core::FollowedMatch {
puuid: "Bob".into(),
match_id: MATCH.into(),
provisional: true,
game_id: Some(GAME),
season: None,
format: arena_tracker_core::Format::Arena3x6,
champion_id: 39,
started_at_ms: 0,
end: arena_tracker_core::MatchEnd::Nothing,
};
window.update(|window, cx| {
page.update(cx, |p, cx| {
let status = p.status.clone();
let round = crate::worker::Msg::Round {
status,
reload: true,
matches: vec![theirs],
game_end: None,
};
p.apply(round, window, cx)
})
});
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
assert!(window.debug_bounds("tab-in-game").is_none());
}
@@ -0,0 +1,138 @@
//! Joueur's game client, driven by the test, and the Live Match the follower reads from it
//! (#109).
use super::champ_select_fixtures::{finish_motion, joueur_tracker, send};
use super::client_fixtures::FakeClient;
use super::page_fixtures::{draw, open_page_with_tracker};
use crate::page::{LiveMatchStarted, Page};
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, GamePhase, Gameflow, LiveMatch};
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
use std::cell::Cell;
use std::rc::Rc;
/// The client's id of Joueur's game.
pub(super) const GAME: u64 = 4242;
/// The client the test drives through game `game`, and the Live Match the follower last told
/// the page.
pub(super) struct Client {
fake: FakeClient,
game: u64,
told: Option<LiveMatch>,
}
impl Client {
pub(super) fn new(fake: FakeClient, game: u64) -> Client {
Client {
fake,
game,
told: None,
}
}
/// The client in `phase` of its game, Arena or not, the player playing `champion`.
pub(super) fn set(&self, phase: GamePhase, arena: bool, champion: Option<u32>) {
*self.fake.flow.lock().unwrap() = Gameflow {
phase,
arena,
game_id: Some(self.game),
queue_id: Some(1750),
champion_id: champion,
};
}
/// The client back in its lobby.
pub(super) fn lobby(&self) {
*self.fake.flow.lock().unwrap() = Gameflow::default();
}
/// The client closes, or opens again signed in as `name`.
pub(super) fn sign_in(&self, name: &str) {
*self.fake.name.lock().unwrap() = name.into();
}
/// A gameflow event: the follower reads the client and tells the page the Live Match when
/// it changed, the champion of the champ select it read before standing in, as the worker
/// does.
pub(super) fn read(&mut self, page: &Entity<Page>, cx: &mut VisualTestContext) {
let (snapshot, picked) = page.read_with(cx, |p, _| {
let picked = p.live_champ_select().and_then(|pick| pick.current);
(p.tracker.client_snapshot(), picked)
});
let Ok(next) = snapshot.live_match(self.told.as_ref(), picked) else {
return;
};
if next != self.told {
self.told = next.clone();
tell(page, cx, next);
}
}
}
/// The follower tells the page the Live Match `live`.
pub(super) fn tell(page: &Entity<Page>, cx: &mut VisualTestContext, live: Option<LiveMatch>) {
cx.update(|window, cx| page.update(cx, |p, cx| p.apply(Msg::LiveMatch(live), window, cx)));
}
/// The page on Joueur's statistics, Joueur in the client's lobby; how many times the page said
/// a Live Match started.
pub(super) async fn joueur_in_lobby(
cx: &mut TestAppContext,
) -> (Entity<Page>, VisualTestContext, Client, Rc<Cell<usize>>) {
joueur_opening(cx, None).await
}
/// The same, the app started while the client plays Joueur's game with `champion`: the page
/// has not read the client yet.
pub(super) async fn joueur_in_game(
cx: &mut TestAppContext,
champion: u32,
) -> (Entity<Page>, VisualTestContext, Client, Rc<Cell<usize>>) {
joueur_opening(cx, Some(champion)).await
}
async fn joueur_opening(
cx: &mut TestAppContext,
playing: Option<u32>,
) -> (Entity<Page>, VisualTestContext, Client, Rc<Cell<usize>>) {
cx.executor().allow_parking();
let fake = FakeClient::new("Joueur");
let client = Client::new(fake.clone(), GAME);
if let Some(champion) = playing {
client.set(GamePhase::InGame, true, Some(champion));
}
let tracker = joueur_tracker().with_client(Box::new(fake));
let (page, mut window) = open_page_with_tracker(cx, tracker);
let started = Rc::new(Cell::new(0));
let counted = started.clone();
window.update(|_, cx| {
cx.subscribe(&page, move |_, _: &LiveMatchStarted, _| {
counted.set(counted.get() + 1)
})
.detach()
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
(page, window, client, started)
}
/// Joueur's page during the champ select `pick`, its hand dealt.
pub(super) async fn joueur_in_champ_select(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext, Client, Rc<Cell<usize>>) {
let (page, mut window, client, started) = joueur_in_lobby(cx).await;
client.set(GamePhase::ChampSelect, true, None);
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
finish_motion(&page, &mut window);
(page, window, client, started)
}
/// Waits for the statistics of the Live Match's scope and for the champion's latest Matches.
pub(super) async fn in_game_ready(page: &Entity<Page>, cx: &mut TestAppContext) {
cx.condition(page, |p, _| p.stats.is_some() && p.in_game.recent_read())
.await;
}
+14
View File
@@ -0,0 +1,14 @@
use gpui_kit::{KeyDownEvent, KeyUpEvent, Keystroke, VisualTestContext};
/// Presses and releases `key` on the element focused, as a button reads it (a keystroke alone
/// does not activate it).
pub(super) fn press_key(cx: &mut VisualTestContext, key: &str) {
let keystroke =
cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke });
}
+22 -14
View File
@@ -1,10 +1,12 @@
use super::banner_fixtures::{
banner_champion, banner_rows, banner_statistics, on, rows_with_splashes,
banner_champion, banner_rows, banner_statistics, last_match_of, on, rows_with_splashes,
};
use super::match_end_fixtures::{
animate, home_names, played, round_with_matches, statistics_arrive, until_landed,
};
use super::page_fixtures::{
animate, animations, assert_at_rest, champions, draw, frame_after, home_names, hover,
open_page_in_season, played, round_with_matches, settle, show, shown_tab, start_switch,
statistics, statistics_arrive, switch_tab, until_landed,
animations, assert_at_rest, champions, draw, frame_after, hover, open_page_in_season, settle,
show, shown_tab, start_switch, statistics, switch_tab,
};
use crate::card_images::tests::TestDir;
@@ -254,11 +256,11 @@ fn a_card_the_filter_leaves_out_stays_until_its_match_has_played(cx: &mut TestAp
assert_eq!(home_names(&page, cx), ["Garen", "Ahri", "Brand"]);
}
// The banner shows the last champion validé. The splash of a champion validé settles in when
// it is that one; a validation older than the banner's, whose Match arrived late, leaves the
// banner on the splash a reload shows.
// The banner shows the last Match's champion. The splash of a champion validé settles in when
// its Match is the last; a Match older than the last, which arrived late, leaves the banner on
// the splash a reload shows.
#[gpui::test]
fn only_the_last_champion_validated_settles_into_the_banner(cx: &mut TestAppContext) {
fn only_the_last_match_settles_into_the_banner(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-late-validation");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
@@ -270,16 +272,22 @@ fn only_the_last_champion_validated_settles_into_the_banner(cx: &mut TestAppCont
(name, art.revealing())
})
};
for (order, expected) in [
(vec![2, 1], ("Ahri.50.30.jpg", true)),
(vec![1, 2], ("Brand.50.30.jpg", false)),
// Ahri's top 1 is the last Match: its splash is revealed. Brand was played after it
// (the top 1 arrived late): Brand's splash, set without a reveal.
for (last, expected) in [
(1, ("Ahri.50.30.jpg", true)),
(2, ("Brand.50.30.jpg", false)),
] {
let mut rows = rows_with_splashes(dir.path());
rows[0] = ChampionRow {
splash: rows[0].splash.clone(),
..banner_champion(1, "Ahri", 2, None, 100)
};
show(&page, cx, banner_statistics(rows, vec![2], None));
show(
&page,
cx,
banner_statistics(rows, vec![2], last_match_of(2)),
);
draw(cx);
round_with_matches(&page, cx, &[(1, MatchEnd::Completed, 1)]);
statistics_arrive(
@@ -287,8 +295,8 @@ fn only_the_last_champion_validated_settles_into_the_banner(cx: &mut TestAppCont
cx,
Some(banner_statistics(
rows_with_splashes(dir.path()),
order,
None,
vec![2, 1],
last_match_of(last),
)),
);
draw(cx);
@@ -0,0 +1,106 @@
//! The end of a followed Match on « Défi »: the rounds that report it and what plays.
use super::page_fixtures::{champions, frame_after, statistics};
use crate::motion::MatchEnd;
use crate::page::Page;
use arena_tracker_core::{Account, FollowedMatch, Statistics, Status};
use gpui_kit::{Entity, VisualTestContext};
/// A follower round reports Matches of the viewed Account, as (champion, what it brought,
/// start), the way the follower does.
pub(super) fn round_with_matches(
page: &Entity<Page>,
cx: &mut VisualTestContext,
matches: &[(u32, MatchEnd, i64)],
) {
use crate::worker::Msg;
let matches = matches
.iter()
.map(|&(champion_id, end, started_at_ms)| FollowedMatch {
puuid: "p".into(),
game_id: None,
season: Some("Saison".into()),
format: arena_tracker_core::Format::Arena3x6,
match_id: format!("EUW1_{started_at_ms}"),
provisional: false,
champion_id,
started_at_ms,
end,
})
.collect();
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = Status {
updating: Some(Account {
puuid: "p".into(),
game_name: "Alice".into(),
tag_line: "EUW".into(),
}),
..page.status.clone()
};
page.apply(
Msg::Round {
status,
reload: false,
matches,
game_end: None,
},
window,
cx,
)
})
});
}
/// The statistics job the round started ends with `stats`, else with those shown.
pub(super) fn statistics_arrive(
page: &Entity<Page>,
cx: &mut VisualTestContext,
stats: Option<Statistics>,
) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let stats = stats
.or_else(|| page.stats.clone())
.unwrap_or_else(|| statistics(0, 5, champions(5)));
page.apply(
crate::worker::Msg::Statistics {
generation: page.stats_generation,
stats: Ok(stats),
home: None,
stored: Some(1),
},
window,
cx,
)
})
});
}
/// The end of a followed Match with champion 1, through the round and the statistics.
pub(super) fn animate(page: &Entity<Page>, cx: &mut VisualTestContext, end: MatchEnd) {
round_with_matches(page, cx, &[(1, end, 0)]);
statistics_arrive(page, cx, None);
}
pub(super) fn played(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<MatchEnd> {
page.read_with(cx, |page, _| page.played.clone())
}
pub(super) fn home_names(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<gpui_kit::SharedString> {
page.read_with(cx, |p, cx| p.home_grid.read(cx).names())
}
/// Frames until the comet of the animation playing lands.
pub(super) fn until_landed(page: &Entity<Page>, cx: &mut VisualTestContext) {
for _ in 0..20 {
frame_after(cx, 100);
if page.read_with(cx, |p, _| p.playback.previous_banner.is_none()) {
return;
}
}
panic!("the comet never landed");
}
+413
View File
@@ -0,0 +1,413 @@
use super::matches_fixtures::{
ALICE, BOB, chosen, listed, open_matches, recap_id, recap_ready, sign_in_bob, tracker,
};
use super::page_fixtures::{
assert_at_rest, center, draw, open_page, open_page_with_tracker, press, show, statistics,
switch_tab,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::local_time::local_time;
use crate::page::Tab;
use crate::page::matches::{Described, Outcome, Recap, Row, ShownPlayer, Slot, UNAVAILABLE};
use crate::text::match_time;
use crate::worker::Msg;
use arena_tracker_core::{Champion, ChampionRow};
use gpui_kit::{Modifiers, SharedString, TestAppContext, VisualTestContext, px, size};
fn click(cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_click(at, Modifiers::none());
draw(cx);
}
/// The Account's player in the recap shown.
fn account_player(
page: &gpui_kit::Entity<crate::page::Page>,
cx: &mut VisualTestContext,
) -> ShownPlayer {
page.read_with(cx, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.is_account)
.unwrap()
.clone()
})
}
#[gpui::test]
fn the_matches_tab_is_right_of_the_challenge_and_lit_alone(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
draw(cx);
let (challenge, matches) = (center(cx, "tab-challenge"), center(cx, "tab-matches"));
assert!(matches.x > challenge.x);
let lit = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, _| (p.lit(Tab::Challenge), p.lit(Tab::Matches)))
};
assert_eq!(lit(cx), (true, false));
click(cx, "tab-matches");
assert_eq!(page.read_with(cx, |p, _| p.tab), Tab::Matches);
assert_eq!(lit(cx), (false, true));
// « Défi » stays lit on its detail page.
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(lit(cx), (true, false));
}
#[gpui::test]
async fn opening_the_tab_lists_the_matches_newest_first_and_opens_the_most_recent(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
assert_eq!(listed(&page, cx), ALICE);
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[0]));
assert_eq!(recap_id(&page, cx).as_deref(), Some(ALICE[0]));
let rows: Vec<Row> = page.read_with(cx, |p, cx| p.matches.list.read(cx).rows().to_vec());
let champions: Vec<_> = rows.iter().map(|r| r.champion.as_ref()).collect();
assert_eq!(champions, ["Irelia", "Ahri", "Irelia"]);
let placements: Vec<_> = rows.iter().map(|r| r.placement.as_ref()).collect();
assert_eq!(placements, ["2ᵉ", "2ᵉ", "2ᵉ"]);
// Its date and time on the player's clock; no Format in the row.
assert_eq!(rows[0].when, match_time(local_time(1_794_763_752_767)));
assert!(rows.iter().all(|r| !r.provisional));
assert!(cx.debug_bounds("match-list").is_some());
assert!(cx.debug_bounds("matches-list-toggle").is_none());
// Nothing runs at rest.
assert_at_rest(cx);
}
#[gpui::test]
async fn the_choice_is_not_kept_from_one_opening_to_the_next(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
click(&mut window, "match-row-2");
assert_eq!(chosen(&page, &mut window).as_deref(), Some(ALICE[2]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[2]));
switch_tab(&page, &mut window, Tab::Challenge);
// Hidden, the screen keeps no recap.
assert!(page.read_with(&window, |p, _| matches!(p.matches.recap, Recap::None)));
switch_tab(&page, &mut window, Tab::Matches);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(ALICE[0]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn the_arrows_move_the_choice_through_the_list(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx2 = &mut window;
// A click gives the list the keyboard.
click(cx2, "match-row-0");
press(cx2, "down");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[1]));
press(cx2, "down");
press(cx2, "down");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[2]));
press(cx2, "up");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[1]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[1]));
}
#[gpui::test]
async fn the_recap_ranks_the_teams_and_highlights_the_account(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
click(&mut window, "match-row-2");
recap_ready(&page, cx).await;
let cx = &mut window;
draw(cx);
page.read_with(cx, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
assert_eq!(shown.champion, "Irelia");
assert!(
shown.details.contains("Arena 3x6 · 23 min 00 s"),
"{}",
shown.details
);
let placements: Vec<_> = shown
.teams
.iter()
.map(|t| t.placement.text.as_ref())
.collect();
assert_eq!(placements, ["1ᵉʳ", "2ᵉ", "3ᵉ"]);
let accounts: Vec<_> = shown.teams.iter().map(|t| t.account).collect();
assert_eq!(accounts, [false, true, false]);
// An old Match names a player by their summoner name.
let names: Vec<_> = (shown.teams[0].players.iter())
.map(|p| p.riot_id.text.as_ref())
.collect();
assert_eq!(names, ["Autre03#FIX", "VieuxNom"]);
});
let me = account_player(&page, cx);
assert_eq!(me.riot_id.text, "Joueur#EUW");
assert_eq!(
[
&me.level,
&me.kda,
me.details.get("Dégâts aux champions", "Total").unwrap()
]
.map(|v| v.text.to_string()),
["18", "12 / 2 / 5", "30\u{202f}000"].map(String::from)
);
let item = |id: u32| {
Slot::Item(Described {
name: SharedString::from(format!("Objet {id}")),
description: None,
icon: None,
})
};
assert_eq!(
me.items,
Ok([
item(3157),
item(3089),
Slot::Empty,
item(3020),
Slot::Empty,
Slot::Empty,
item(3340)
])
);
let augments: Vec<_> = ["Amélioration 101", "Amélioration 212", "Amélioration 305"]
.map(|name| Described {
name: name.into(),
description: None,
icon: None,
})
.to_vec();
assert_eq!(me.augments, Ok(augments));
assert!(cx.debug_bounds("recap-account").is_some());
assert!(cx.debug_bounds("recap-provisional").is_none());
}
#[gpui::test]
async fn a_match_without_statistics_says_they_are_unavailable(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let me = account_player(&page, &mut window);
for value in [
&me.level,
&me.kda,
me.details.get("Dégâts aux champions", "Total").unwrap(),
] {
assert_eq!((value.text.as_ref(), value.missing), (UNAVAILABLE, true));
}
assert_eq!(me.items.as_ref().unwrap_err().text, UNAVAILABLE);
assert_eq!(me.augments.as_ref().unwrap_err().text, UNAVAILABLE);
// Its Riot ID is given.
assert_eq!(me.riot_id.text, "Joueur#EUW");
}
#[gpui::test]
async fn a_new_account_in_the_client_switches_the_list_without_mixing(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (tracker, signed_in) = tracker();
let (page, mut window) = open_page_with_tracker(cx, tracker);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), ALICE);
sign_in_bob(&page, &signed_in, &mut window);
// At once: none of Alice's Matches stays.
assert!(listed(&page, &mut window).is_empty());
assert_eq!(chosen(&page, &mut window), None);
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), [BOB]);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(BOB));
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(BOB));
}
#[gpui::test]
async fn known_matches_stay_during_a_sync_and_after_a_failure(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
cx.update(|window, cx| {
page.update(cx, |page, cx| {
// Something stored changed: the list is read again, the Matches stay meanwhile.
page.apply(Msg::Champions, window, cx);
assert_eq!(page.matches.entries().map(<[_]>::len), Some(3));
let generation = page.matches.generation();
page.apply(
Msg::Matches {
generation,
matches: Err("Parties indisponibles : base verrouillée".into()),
},
window,
cx,
);
assert_eq!(page.matches.entries().map(<[_]>::len), Some(3));
assert!(page.matches.error().is_some());
})
});
draw(cx);
assert!(cx.debug_bounds("matches-error").is_some());
assert!(cx.debug_bounds("match-row-0").is_some());
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
fn without_an_account_the_screen_says_so(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
switch_tab(&page, cx, Tab::Matches);
draw(cx);
assert!(cx.debug_bounds("banner").is_some());
assert!(cx.debug_bounds("matches-notice").is_some());
assert!(cx.debug_bounds("match-list").is_none());
}
#[gpui::test]
async fn a_narrow_window_puts_the_list_behind_a_button(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
cx.simulate_resize(size(px(800.), px(700.)));
draw(cx);
assert!(cx.debug_bounds("match-list").is_none());
click(cx, "matches-list-toggle");
assert!(cx.debug_bounds("matches-list-over").is_some());
// Choosing a Match closes the list.
click(cx, "match-row-1");
assert!(cx.debug_bounds("matches-list-over").is_none());
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[1]));
}
#[gpui::test]
async fn the_list_builds_only_its_rows_in_view_and_is_not_drawn_with_the_page(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
let list = page.read_with(cx, |p, _| p.matches.list.clone());
let rows: Vec<Row> = (0..300)
.map(|ix| Row {
match_id: format!("EUW1_{ix}"),
champion: "Irelia".into(),
portrait: None,
when: "15 nov. 2026 · 17:29".into(),
placement: "2ᵉ".into(),
outcome: Outcome::Win,
provisional: ix == 0,
})
.collect();
cx.update(|_, cx| list.update(cx, |list, cx| list.set_rows(rows, Some("EUW1_0"), cx)));
draw(cx);
assert!(cx.debug_bounds("match-row-0").is_some());
assert!(cx.debug_bounds("match-row-200").is_none());
// The page drawn again (the recap arriving, the veil) does not draw the list.
let renders = |cx: &mut VisualTestContext| list.read_with(cx, |list, _| list.renders);
let before = renders(cx);
cx.update(|_, cx| page.update(cx, |_, cx| cx.notify()));
draw(cx);
assert_eq!(renders(cx), before);
}
/// Irelia's portrait shown in the list and the recap; how many portraits each holds.
fn with_portraits(
page: &gpui_kit::Entity<crate::page::Page>,
cx: &mut VisualTestContext,
dir: &TestDir,
) -> impl Fn(&mut VisualTestContext) -> (usize, usize) + use<> {
let path = dir.path().join("Irelia.png");
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
let mut irelia = crate::champion_table::tests::row("Irelia");
irelia.champion = Champion {
id: 39,
key: "Irelia".into(),
name: "Irelia".into(),
};
irelia.portrait = Some(path);
let rows: Vec<ChampionRow> = vec![irelia];
show(page, cx, statistics(0, 1, rows));
draw(cx);
cx.run_until_parked();
draw(cx);
let (list_images, recap_images) = page.read_with(cx, |p, cx| {
let list = p.matches.list.read(cx).images().cloned().unwrap();
(list, p.matches.recap_images(cx))
});
move |cx: &mut VisualTestContext| {
(
list_images.read_with(cx, |images, _| images.held().len()),
recap_images.read_with(cx, |images, _| images.held().len()),
)
}
}
#[gpui::test]
async fn the_portraits_go_with_the_screen(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
let dir = TestDir::new("matches-portraits");
let held = with_portraits(&page, cx, &dir);
let (list, recap) = held(cx);
assert!(list > 0 && recap > 0, "{list} {recap}");
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(held(cx), (0, 0));
}
#[gpui::test]
async fn a_list_closed_in_a_narrow_window_gives_its_portraits_back(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
let dir = TestDir::new("matches-narrow-portraits");
let held = with_portraits(&page, cx, &dir);
assert!(held(cx).0 > 0);
cx.simulate_resize(size(px(800.), px(700.)));
draw(cx);
cx.run_until_parked();
let (list, recap) = held(cx);
assert_eq!(list, 0, "the list closed holds no portrait");
assert!(recap > 0, "the recap still shows its own");
assert!(cx.debug_bounds("matches-season").is_none(), "not built");
}
#[gpui::test]
async fn the_account_chosen_in_the_top_bar_is_the_one_whose_matches_are_listed(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
// Bob is chosen while Alice stays signed in to the client.
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.show_account(Some("Bob".into()), window, cx)
})
});
draw(&mut window);
// At once: none of Alice's Matches stays.
assert!(listed(&page, &mut window).is_empty());
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), [BOB]);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(BOB));
// The selector says whose Matches they are, on « Parties » as on the Challenge.
let selected = |page: &gpui_kit::Entity<crate::page::Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
(p.account_select.read(cx).selected_value()).map(|v| v.to_string())
})
};
assert_eq!(selected(&page, &mut window).as_deref(), Some("Bob"));
switch_tab(&page, &mut window, Tab::Challenge);
assert_eq!(selected(&page, &mut window).as_deref(), Some("Bob"));
}
#[gpui::test]
async fn a_list_arriving_once_the_screen_left_starts_nothing(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, tracker().0);
switch_tab(&page, &mut window, Tab::Matches);
switch_tab(&page, &mut window, Tab::Challenge);
cx.condition(&page, |p, _| !p.matches.reading()).await;
page.read_with(&window, |p, _| {
// Dropped: no Match is chosen, and none is decoded.
assert_eq!(p.matches.selected, None);
assert!(matches!(p.matches.recap, Recap::None));
});
// Back on the screen, the list is read again and the most recent opens.
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
@@ -0,0 +1,453 @@
//! The end of a Match opens its recap (#129): its end-of-game block shows « Parties » with the new
//! Match chosen, from any screen, and never brings the window forward.
use super::client_fixtures::FakeClient;
use super::matches_fixtures::{ALICE, chosen, listed, recap_id};
use super::matches_provisional::{GAME, LEFT_AT_MS, MATCH, block, tracker_before_block};
use super::page_fixtures::{draw, frame_after, open_page_with_tracker, season, switch_tab};
use crate::page::ALL_SEASONS;
use crate::page::matches::Recap;
use crate::page::{Page, RecapOpened, Tab};
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, FollowedMatch, Format, GameEnd, MatchEnd, SeasonScope};
use gpui_kit::component::select::SelectEvent;
use gpui_kit::{Entity, TestAppContext, VisualTestContext, WindowVisibility};
use std::cell::Cell;
use std::rc::Rc;
/// The page on Alice's Matches before the game ends, Alice's client, which holds its block, and
/// how many times the page said it opened a recap.
pub(super) fn before_the_end(
cx: &mut TestAppContext,
) -> (Entity<Page>, VisualTestContext, FakeClient, Rc<Cell<usize>>) {
before_the_end_in(cx, vec![season("Saison", 2020)])
}
fn before_the_end_in(
cx: &mut TestAppContext,
seasons: Vec<arena_tracker_core::Season>,
) -> (Entity<Page>, VisualTestContext, FakeClient, Rc<Cell<usize>>) {
cx.executor().allow_parking();
let (tracker, _, client) = tracker_before_block(seasons);
let (page, mut window) = open_page_with_tracker(cx, tracker);
let opened = Rc::new(Cell::new(0));
let counted = opened.clone();
window.update(|_, cx| {
cx.subscribe(&page, move |_, _: &RecapOpened, _| {
counted.set(counted.get() + 1)
})
.detach()
});
// The player is in League: the window is not the active one.
window.deactivate_window();
draw(&mut window);
(page, window, client, opened)
}
/// The game ends: the client gives its end-of-game block, and the follower's round stores its
/// Provisional Match and tells the page, as the worker does.
pub(super) fn game_ends(page: &Entity<Page>, client: &FakeClient, cx: &mut VisualTestContext) {
*client.block.lock().unwrap() = Some(block());
let ended = round(page, cx, LEFT_AT_MS);
assert_eq!(ended.len(), 1);
assert_eq!(
(ended[0].match_id.as_str(), ended[0].provisional),
(MATCH, true)
);
}
/// A follower round at `now_ms`, applied by the page; the Matches it reported.
fn round(page: &Entity<Page>, cx: &mut VisualTestContext, now_ms: i64) -> Vec<FollowedMatch> {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let (snapshot, mut ended) = (page.tracker.client_snapshot(), Vec::new());
let changed =
(page.tracker).follow_client_with(now_ms, None, &snapshot, &mut |_| {}, &mut |m| {
ended.push(m)
});
let status = page.tracker.status();
let matches = ended.clone();
page.apply(
Msg::Round {
status,
reload: changed,
matches,
game_end: None,
},
window,
cx,
);
ended
})
})
}
/// Lets the transition between the tabs end.
pub(super) fn settle_tabs(page: &Entity<Page>, cx: &mut VisualTestContext) {
for _ in 0..10 {
if page.read_with(cx, |p, _| p.fade.is_none()) {
return draw(cx);
}
frame_after(cx, 50);
}
panic!("the transition did not end");
}
/// Waits for the recap of the Match that ended.
pub(super) async fn its_recap(page: &Entity<Page>, cx: &mut TestAppContext) {
cx.condition(
page,
|p, _| matches!(&p.matches.recap, Recap::Ready { recap, .. } if recap.match_id == MATCH),
)
.await;
}
pub(super) fn tabs(page: &Entity<Page>, cx: &mut VisualTestContext) -> (Tab, Tab) {
page.read_with(cx, |p, _| (p.tab, p.shown_tab))
}
/// The window was neither activated nor shown, and nothing in it took the focus.
pub(super) fn left_alone(cx: &mut VisualTestContext, visible: bool) {
cx.update(|window, cx| {
assert_eq!(cx.active_window(), None, "the window was activated");
assert!(!window.is_window_active());
assert_eq!(window.is_visible(), visible);
assert_eq!(window.focused(cx), None);
});
}
#[gpui::test]
async fn the_end_of_a_match_opens_its_recap_from_the_challenge(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
draw(&mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(listed(&page, &mut window)[0], MATCH);
assert!(window.debug_bounds("recap-provisional").is_some());
assert_eq!(opened.get(), 1);
left_alone(&mut window, true);
}
#[gpui::test]
async fn the_end_of_a_match_opens_its_recap_from_the_statistics(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
switch_tab(&page, &mut window, Tab::Statistics);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(opened.get(), 1);
left_alone(&mut window, true);
}
#[gpui::test]
async fn the_end_of_a_match_replaces_an_older_recap_and_the_search_that_hides_it(
cx: &mut TestAppContext,
) {
let (page, mut window, client, opened) = before_the_end(cx);
switch_tab(&page, &mut window, Tab::Matches);
cx.condition(&page, |p, _| matches!(p.matches.recap, Recap::Ready { .. }))
.await;
// Only Ahri's Match, an older one, is left and shown; the new Match is Irelia's.
let input = page.read_with(&window, |p, _| p.matches.search_input().clone());
window.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
window.simulate_input("Ahri");
draw(&mut window);
assert_eq!(listed(&page, &mut window), [ALICE[1]]);
cx.condition(
&page,
|p, _| matches!(&p.matches.recap, Recap::Ready { recap, .. } if recap.match_id == ALICE[1]),
)
.await;
game_ends(&page, &client, &mut window);
// Nothing older shows while the list is read again.
assert_eq!(
page.read_with(&window, |p, _| p.matches.selected.clone()),
None
);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
draw(&mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
// The search emptied: every Match is listed.
assert_eq!(
input.read_with(&window, |input, _| input.value()).as_ref(),
""
);
let mut all = vec![MATCH.to_string()];
all.extend(ALICE.map(String::from));
assert_eq!(listed(&page, &mut window), all);
assert_eq!(opened.get(), 1);
}
#[gpui::test]
async fn behind_the_settings_or_in_a_hidden_window_the_switch_is_at_once(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
// « Paramètres » stands in for the page, in a window hidden in the notification area.
window.update(|window, cx| page.update(cx, |page, cx| page.hidden(window, cx)));
window.simulate_visibility_change(WindowVisibility::Hidden);
game_ends(&page, &client, &mut window);
// No veil to wait for: « Parties » is there, and the page asks « Paramètres » to give way.
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert!(page.read_with(&window, |p, _| p.fade.is_none()));
assert_eq!(opened.get(), 1);
its_recap(&page, cx).await;
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
left_alone(&mut window, false);
}
#[gpui::test]
async fn with_the_preference_off_the_challenge_shows_and_the_match_is_listed(
cx: &mut TestAppContext,
) {
let (page, mut window, client, opened) = before_the_end(cx);
page.update(&mut window, |page, _| {
page.set_open_recap_at_match_end(false)
});
switch_tab(&page, &mut window, Tab::Statistics);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
// In the history all the same: « Parties » opened by hand chooses it, the most recent.
switch_tab(&page, &mut window, Tab::Matches);
its_recap(&page, cx).await;
assert_eq!(listed(&page, &mut window)[0], MATCH);
}
#[gpui::test]
async fn a_match_found_without_its_block_leaves_the_challenge(cx: &mut TestAppContext) {
let (page, mut window, _, opened) = before_the_end(cx);
// As when Riot publishes the Match of a game whose block never came.
let published = FollowedMatch {
puuid: "Alice".into(),
match_id: ALICE[0].into(),
provisional: false,
game_id: None,
season: Some("Saison".into()),
format: Format::Arena3x6,
champion_id: 39,
started_at_ms: 0,
end: MatchEnd::Nothing,
};
window.update(|window, cx| {
page.update(cx, |page, cx| {
let status = page.tracker.status();
let matches = vec![published];
page.apply(
Msg::Round {
status,
reload: true,
matches,
game_end: None,
},
window,
cx,
);
})
});
draw(&mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
}
/// The client left the game `game_id`; no end-of-game block came.
fn game_ends_without_its_block(page: &Entity<Page>, cx: &mut VisualTestContext, game_id: u64) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = page.tracker.status();
let game_end = Some(GameEnd {
game_id: Some(game_id),
});
page.apply(
Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end,
},
window,
cx,
);
})
});
}
#[gpui::test]
async fn a_game_that_ends_without_its_block_shows_the_challenge(cx: &mut TestAppContext) {
let (page, mut window, _, opened) = before_the_end(cx);
switch_tab(&page, &mut window, Tab::Statistics);
game_ends_without_its_block(&page, &mut window, 9_000_000_021);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
// From an older recap too.
switch_tab(&page, &mut window, Tab::Matches);
cx.condition(&page, |p, _| matches!(p.matches.recap, Recap::Ready { .. }))
.await;
game_ends_without_its_block(&page, &mut window, 9_000_000_022);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
left_alone(&mut window, true);
}
#[gpui::test]
async fn the_end_of_a_game_whose_recap_opened_leaves_it_open(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
// The client leaves the game after its block came: decided already.
game_ends_without_its_block(&page, &mut window, GAME);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(opened.get(), 1);
}
#[gpui::test]
async fn a_match_that_no_season_holds_opens_under_every_season(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end_in(cx, Vec::new());
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(opened.get(), 1);
}
#[gpui::test]
async fn nothing_brings_the_player_back_to_the_matches_afterwards(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
switch_tab(&page, &mut window, Tab::Challenge);
// Later rounds, which read the stored Matches again, and a refresh.
for later in 1..=3 {
round(&page, &mut window, LEFT_AT_MS + later * 20_000);
}
window.update(|window, cx| {
page.update(cx, |page, cx| {
let status = page.tracker.status();
page.apply(Msg::Refreshed(status), window, cx);
})
});
draw(&mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 1);
assert_eq!(recap_id(&page, &mut window), None);
}
#[gpui::test]
async fn a_season_that_hides_the_new_match_gives_way_to_the_current_one(cx: &mut TestAppContext) {
let (page, mut window, client, opened) =
before_the_end_in(cx, vec![season("Ancienne", 2020), season("Saison", 2026)]);
switch_tab(&page, &mut window, Tab::Matches);
// The player looks at the older Season, the same selector as « Statistiques ».
let select = page.read_with(&window, |p, _| p.season_select.clone());
window.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some("Ancienne".into())))
})
});
draw(&mut window);
assert_eq!(
page.read_with(&window, |p, _| p.season.clone()),
SeasonScope::Season("Ancienne".into())
);
assert!(listed(&page, &mut window).is_empty());
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
draw(&mut window);
// The selectors show the current Season for both pages, and the new Match is the one chosen.
page.read_with(&window, |p, cx| {
assert_eq!(p.season, SeasonScope::Season("Saison".into()));
assert_eq!(p.format, None);
let selected = p.season_select.read(cx).selected_value();
assert_eq!(selected.map(|s| s.as_ref()), Some("Saison"));
});
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(listed(&page, &mut window)[0], MATCH);
assert_eq!(opened.get(), 1);
}
#[gpui::test]
async fn a_season_that_keeps_the_new_match_is_left_as_it_is(cx: &mut TestAppContext) {
let (page, mut window, client, _) =
before_the_end_in(cx, vec![season("Ancienne", 2020), season("Saison", 2026)]);
// « Toutes les Saisons » holds it too.
let select = page.read_with(&window, |p, _| p.season_select.clone());
window.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some(ALL_SEASONS.into())))
})
});
draw(&mut window);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
assert_eq!(
page.read_with(&window, |p, _| p.season.clone()),
SeasonScope::AllSeasons
);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
}
#[gpui::test]
async fn during_a_champ_select_the_end_of_a_match_opens_nothing(cx: &mut TestAppContext) {
let (page, mut window, client, opened) = before_the_end(cx);
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(
Msg::ChampSelect(Some(("Alice#EUW".into(), pick))),
window,
cx,
)
})
});
draw(&mut window);
let before = tabs(&page, &mut window);
game_ends(&page, &client, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), before);
assert_ne!(before.0, Tab::Matches);
assert_eq!(opened.get(), 0);
assert_eq!(
page.read_with(&window, |p, _| p.matches.arriving().map(String::from)),
None
);
}
+122
View File
@@ -0,0 +1,122 @@
//! The banner of « Parties » (#110): the Défi's, on the champion of the Match chosen.
use super::banner_fixtures::{banner_champion, banner_statistics, on, ring_ticks, splash};
use super::matches_fixtures::{ALICE, chosen, recap_ready, tracker_in};
use super::page_fixtures::{draw, open_page_with_tracker, season, show, switch_tab, tall};
use crate::card_images::tests::TestDir;
use crate::page::{Page, Tab};
use arena_tracker_core::ChampionRow;
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
/// Irelia (39) and Ahri (103), each with a splash, then Garen without one; Alice's Matches are
/// Irelia's, Ahri's and Irelia's.
pub(super) fn rows(dir: &TestDir) -> Vec<ChampionRow> {
let mut rows = vec![
banner_champion(39, "Irelia", 2, None, 100),
banner_champion(103, "Ahri", 1, Some(on(11, 3)), 5),
banner_champion(4, "Garen", 2, None, 900),
];
rows[0].splash = Some(splash(dir.path(), "Irelia"));
rows[1].splash = Some(splash(dir.path(), "Ahri"));
rows
}
/// « Parties » on Alice's Matches, in a Season, under statistics whose champions have splashes.
pub(super) async fn on_matches(
cx: &mut TestAppContext,
dir: &TestDir,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (tracker, _) = tracker_in(false, vec![season("Saison", 2020)]);
let (page, mut window) = open_page_with_tracker(cx, tracker);
tall(&mut window);
show(
&page,
&mut window,
banner_statistics(rows(dir), vec![103], None),
);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
(page, window)
}
/// The splash the banner aims at, and the tick lit.
pub(super) fn dressed(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> (Option<String>, Option<u32>) {
page.read_with(cx, |p, cx| {
let target = p.banner_art.read(cx).target.as_ref();
(
target.map(|s| s.path.file_name().unwrap().to_string_lossy().into_owned()),
p.ring.read(cx).lit(),
)
})
}
#[gpui::test]
async fn the_banner_is_the_challenges_over_the_chosen_matchs_champion(cx: &mut TestAppContext) {
let dir = TestDir::new("matches-banner");
let (page, mut cx) = on_matches(cx, &dir).await;
let cx = &mut cx;
// The Défi's text and ring, and its link to « Statistiques ».
for id in ["banner", "banner-season", "banner-title", "statistics-link"] {
assert!(cx.debug_bounds(id).is_some(), "{id}");
}
assert_eq!(ring_ticks(&page, cx).len(), 3);
assert_eq!(
page.read_with(cx, |p, _| p.shown_banner().title.text.clone()),
page.read_with(cx, |p, _| p.banner.title.text.clone())
);
// The list, under the banner, keeps its own place.
let (banner, list) = (
cx.debug_bounds("banner").unwrap(),
cx.debug_bounds("match-list").unwrap(),
);
assert!(list.top() >= banner.bottom());
// The most recent Match is Irelia's.
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[0]));
assert_eq!(
dressed(&page, cx),
(Some("Irelia.50.30.jpg".into()), Some(39))
);
// Another Match chosen: its champion's illustration and tick.
let at = super::page_fixtures::center(cx, "match-row-1");
cx.simulate_click(at, Modifiers::none());
draw(cx);
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[1]));
assert_eq!(
dressed(&page, cx),
(Some("Ahri.50.30.jpg".into()), Some(103))
);
}
#[gpui::test]
async fn without_a_match_chosen_no_illustration_and_no_tick_are_lit(cx: &mut TestAppContext) {
let dir = TestDir::new("matches-banner-none");
let (page, mut cx) = on_matches(cx, &dir).await;
let cx = &mut cx;
assert!(dressed(&page, cx).0.is_some());
// A search that keeps no Match.
let search = page.read_with(cx, |p, _| p.matches.search_input().clone());
cx.update(|window, cx| search.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("zzz");
draw(cx);
assert_eq!(chosen(&page, cx), None);
assert_eq!(dressed(&page, cx), (None, None));
// The banner stays, with the Défi's text.
assert!(cx.debug_bounds("banner-season").is_some());
}
#[gpui::test]
async fn the_challenge_keeps_its_own_illustration_and_no_tick(cx: &mut TestAppContext) {
let dir = TestDir::new("matches-banner-challenge");
let (page, mut cx) = on_matches(cx, &dir).await;
let cx = &mut cx;
switch_tab(&page, cx, Tab::Challenge);
draw(cx);
// No Match was played in the statistics: the Défi has no last Match, hence no illustration.
assert_eq!(dressed(&page, cx), (None, None));
}
+247
View File
@@ -0,0 +1,247 @@
//! The bubble of an item or an augment, shown on hover (#132, #133): in the recap of « Parties »
//! and in « Dégâts observés dans les récaps de mort ».
use super::matches_death_recap::{Script, open};
use super::matches_fixtures::tracker;
use super::matches_game_data::{cache, open_full_recap};
use super::page_fixtures::{center, draw, open_page_launched, switch_tab};
use crate::card_images::tests::TestDir;
use crate::page::matches::{ShownDamage, Slot, augment_selector, item_selector};
use crate::page::{Page, Tab};
use arena_tracker_core::GameData;
use gpui_kit::{
Entity, Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px, size,
};
use std::time::Duration;
/// A selector made at run time: the tests are short-lived.
fn selector(name: String) -> &'static str {
Box::leak(name.into_boxed_str())
}
/// Moves the pointer over the element and waits past the delay of the tooltips.
fn hover(window: &mut VisualTestContext, id: &'static str) {
let at = center(window, id);
window.simulate_mouse_move(at, None, Modifiers::none());
window.executor().advance_clock(Duration::from_secs(1));
window.run_until_parked();
draw(window);
}
/// What the open bubble shows under the name (which must be there): its description, or the
/// word for its absence.
fn bubble(window: &mut VisualTestContext) -> &'static str {
assert!(window.debug_bounds("bubble-name").is_some(), "no bubble");
match (
window.debug_bounds("bubble-description").is_some(),
window.debug_bounds("bubble-unavailable").is_some(),
) {
(true, false) => "description",
(false, true) => "indisponible",
other => panic!("the bubble shows {other:?}"),
}
}
/// The index of the Account's line in the recap.
fn account_line(page: &Entity<Page>, window: &mut VisualTestContext) -> usize {
page.read_with(window, |p, cx| {
(p.matches.shown(cx).unwrap().teams.iter())
.flat_map(|team| team.players.iter())
.position(|player| player.is_account)
.unwrap()
})
}
#[gpui::test]
async fn an_item_and_an_augment_of_the_recap_show_their_description_on_hover(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("bubble-recap");
let (page, mut window) = open_page_launched(cx, tracker().0, None, Some(cache(&dir)));
switch_tab(&page, &mut window, Tab::Matches);
cx.condition(&page, |p, _| !p.matches.catalog().is_empty())
.await;
open_full_recap(&page, cx, &mut window).await;
let me = account_line(&page, &mut window);
// Prepared with the catalog: the tags are gone and the line breaks stay.
let player = page.read_with(&window, |p, cx| {
(p.matches.shown(cx).unwrap().teams.iter())
.flat_map(|team| team.players.iter())
.nth(me)
.unwrap()
.clone()
});
let items = player.items.unwrap();
let described = |slot: &Slot| match slot {
Slot::Item(item) => item.description.as_deref().map(str::to_owned),
other => panic!("not an item: {other:?}"),
};
assert_eq!(
described(&items[1]).as_deref(),
Some("+120 puissance\n\nOpus magique\nGagnez ? pts.")
);
assert_eq!(described(&items[3]), None);
let augments = player.augments.unwrap();
assert_eq!(
augments[1].description.as_deref(),
Some("Gagnez 20% de dégâts (?).")
);
// Built on hover only.
assert!(window.debug_bounds("bubble-name").is_none());
// An item with its description, drawn over several lines.
hover(&mut window, selector(item_selector(me, 1)));
assert_eq!(bubble(&mut window), "description");
let name = window.debug_bounds("bubble-name").unwrap();
let text = window.debug_bounds("bubble-description").unwrap();
assert!(
text.size.height > name.size.height * 3.,
"{text:?} {name:?}"
);
// Named, without a description: the word, in gray.
hover(&mut window, selector(item_selector(me, 3)));
assert_eq!(bubble(&mut window), "indisponible");
// The augments: with their summary, and unknown to the catalog.
hover(&mut window, selector(augment_selector(me, 1)));
assert_eq!(bubble(&mut window), "description");
hover(&mut window, selector(augment_selector(me, 0)));
assert_eq!(bubble(&mut window), "indisponible");
}
#[gpui::test]
async fn only_items_and_augments_inside_the_recap_viewport_register_tooltips(
cx: &mut TestAppContext,
) {
let (page, mut window) = super::matches_fixtures::open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
let (first, last) = page.read_with(&window, |p, cx| {
let mut players = p
.matches
.shown(cx)
.unwrap()
.teams
.iter()
.flat_map(|team| team.players.iter())
.enumerate()
.filter(|(_, player)| player.augments.as_ref().is_ok_and(|a| !a.is_empty()))
.filter_map(|(ix, player)| {
let item = player
.items
.as_ref()
.ok()?
.iter()
.position(|slot| matches!(slot, Slot::Item(_)))?;
Some((
ix,
[
selector(augment_selector(ix, 0)),
selector(item_selector(ix, item)),
],
))
});
(players.next().unwrap().1, players.last().unwrap())
});
let (last_player, last) = last;
// The recap's viewport is 380 px high, under the banner.
let banner = window.debug_bounds("banner").unwrap().size.height;
window.simulate_resize(size(px(1280.), px(380.) + banner + px(12.)));
draw(&mut window);
// Both rows are laid out, but only the first row installed tooltips.
let at = center(&mut window, first[0]);
assert!(window.debug_bounds(first[1]).is_some());
assert!(
window
.debug_bounds(selector(format!("recap-player-{last_player}")))
.is_some()
);
assert!(last.iter().all(|id| window.debug_bounds(id).is_none()));
window.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(-5000.))),
..Default::default()
});
draw(&mut window);
assert!(first.iter().all(|id| window.debug_bounds(id).is_none()));
for id in last {
hover(&mut window, id);
assert_eq!(bubble(&mut window), "indisponible");
}
}
/// The catalog of the Death Recap tests: the item the timeline matches, and the augment it names;
/// `summary` is the augment's, empty for none.
fn death_cache(dir: &TestDir, summary: &str) -> GameData {
let augment = format!(
r#"{{"id": 212, "name_id": "Augment_Foxfire_Spell", "name": "Renard de feu",
"rarity": null, "summary": "{summary}", "icon": ""}}"#
);
std::fs::write(
dir.path().join("catalog.json"),
format!(
r#"{{"version": "16.22.1", "icons_complete": true,
"items": [{{"id": 223107, "name": "Rédemption", "icon": "",
"description": "<mainText>Soigne <healing>0 pts</healing><br>Passif</mainText>"}}],
"augments": [{augment}]}}"#
),
)
.unwrap();
GameData::new(dir.path().to_owned())
}
#[gpui::test]
async fn the_item_and_augment_lines_of_the_death_recaps_show_their_bubble_on_hover(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("bubble-death-recap");
let mut app = open(cx, Script::Serve, Some(death_cache(&dir, "Gagne @X@ or."))).await;
app.open_row(cx, 2).await;
app.unfold("Joueur");
let line = |app: &mut super::matches_death_recap::Opened, name: &str| {
app.page.read_with(&app.window, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.riot_id.text.starts_with("Joueur"))
.map(|player| match &player.damage_seen {
ShownDamage::Seen(lines) => lines
.iter()
.position(|l| l.described.name == name)
.map(|ix| (ix, lines[ix].described.description.clone())),
other => panic!("no lines: {other:?}"),
})
.unwrap()
.unwrap()
})
};
let (augment, summary) = line(&mut app, "Renard de feu");
let (item, description) = line(&mut app, "Rédemption");
assert_eq!(summary.as_deref(), Some("Gagne ? or."));
assert_eq!(description.as_deref(), Some("Soigne ? pts\nPassif"));
assert!(app.window.debug_bounds("bubble-name").is_none());
hover(&mut app.window, selector(format!("death-effect-{item}")));
assert_eq!(bubble(&mut app.window), "description");
hover(&mut app.window, selector(format!("death-effect-{augment}")));
assert_eq!(bubble(&mut app.window), "description");
// « Autres effets » has none.
let others = selector(format!("death-effect-{}", item.max(augment) + 1));
assert!(app.window.debug_bounds(others).is_some());
hover(&mut app.window, others);
assert!(app.window.debug_bounds("bubble-name").is_none());
}
#[gpui::test]
async fn an_effect_without_description_says_so_in_its_bubble(cx: &mut TestAppContext) {
let dir = TestDir::new("bubble-death-recap-bare");
let mut app = open(cx, Script::Serve, Some(death_cache(&dir, ""))).await;
app.open_row(cx, 2).await;
app.unfold("Joueur");
// The augment comes first (180 against 120).
hover(&mut app.window, "death-effect-0");
assert_eq!(bubble(&mut app.window), "indisponible");
}
@@ -0,0 +1,490 @@
//! The « Dégâts observés dans les récaps de mort » of a player's details (#128): the damage
//! of the timeline's Death Recaps by item and augment, and the states of the section.
use super::client_fixtures::FakeClient;
use super::matches_fixtures::{TwoAccounts, recap_ready};
use super::page_fixtures::{center, draw, open_page_launched, switch_tab, tall};
use crate::card_images::tests::TestDir;
use crate::page::matches::{Death, NONE_SEEN, OTHERS, Recap, ShownDamage, UNAVAILABLE};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{
Account, DeathRecapState, GameCatalog, GameData, MatchHistorySource, SourceError, Tracker,
};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
use std::path::Path;
use std::sync::{Arc, Mutex};
/// Two kills of the full-recap Match (the oldest of Alice): what Irelia (participant 2: the
/// augment `augment_foxfire_spell`, ItemRedemption22, a basic attack and `augment_nowyouseeme`),
/// Lissandra (participant 1) and a minion dealt to the victims.
const TIMELINE: &str =
include_str!("../../../../core/tests/fixtures/riot/timeline_1750_EUW1_9000000007.json");
/// The Matches of Alice (newest first): the one opened first, then the full recap.
const FIRST: &str = "EUW1_9000000006";
const FULL: &str = "EUW1_9000000007";
const ROWS: [&str; 3] = ["match-row-0", "match-row-1", "match-row-2"];
const LINES: [&str; 6] = [
"recap-player-0",
"recap-player-1",
"recap-player-2",
"recap-player-3",
"recap-player-4",
"recap-player-5",
];
/// What Riot answers to a timeline request.
#[derive(Clone, Copy, Debug)]
pub(super) enum Script {
Serve,
/// Riot refuses the timeline, and the Match itself is there: a refusal.
Refuse,
/// The next `n` requests fail on the network.
Fail(usize),
}
/// Alice's history with timelines.
struct Timelines {
script: Arc<Mutex<Script>>,
asked: Arc<Mutex<Vec<String>>>,
}
impl MatchHistorySource for Timelines {
fn resolve_account(&self, name: &str, tag: &str) -> Result<Account, SourceError> {
TwoAccounts { more: false }.resolve_account(name, tag)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
since: Option<i64>,
) -> Result<Vec<String>, SourceError> {
TwoAccounts { more: false }.match_ids(puuid, queue_id, start, count, since)
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let payload = TwoAccounts { more: false }.fetch_match(id)?;
// The Redemption item of Arena, in the first slot of every player of the full recap.
Ok(payload.replace("\"item0\": 3157", "\"item0\": 223107"))
}
fn fetch_timeline(&self, id: &str) -> Result<String, SourceError> {
self.asked.lock().unwrap().push(id.into());
let mut script = self.script.lock().unwrap();
match *script {
Script::Serve => Ok(TIMELINE.into()),
Script::Refuse => Err(SourceError::InvalidKey),
Script::Fail(n) => {
*script = if n > 1 {
Script::Fail(n - 1)
} else {
Script::Serve
};
Err(SourceError::Network("hors ligne".into()))
}
}
}
}
/// A cache whose augment 212 is the one the timeline names, and with the item the exceptions
/// table matches.
fn cache(dir: &TestDir) -> GameData {
std::fs::write(
dir.path().join("catalog.json"),
r#"{"version": "16.22.1", "icons_complete": true,
"items": [{"id": 223107, "name": "Rédemption", "icon": ""}],
"augments": [{"id": 212, "name_id": "Augment_Foxfire_Spell", "name": "Renard de feu",
"rarity": null, "icon": ""}]}"#,
)
.unwrap();
GameData::new(dir.path().to_owned())
}
pub(super) struct Opened {
pub(super) page: Entity<Page>,
pub(super) window: VisualTestContext,
asked: Arc<Mutex<Vec<String>>>,
}
impl Opened {
fn asked(&self, id: &str) -> usize {
self.asked
.lock()
.unwrap()
.iter()
.filter(|a| *a == id)
.count()
}
fn damage_of(&mut self, name: &str) -> ShownDamage {
self.page.read_with(&self.window, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.riot_id.text.starts_with(name))
.unwrap()
.damage_seen
.clone()
})
}
/// The Death Recap of the Match opened is known, or its fetch failed.
async fn settled(&mut self, cx: &mut TestAppContext) {
cx.condition(&self.page, |p, _| {
matches!(p.matches.death(), Some(Death::Known(_) | Death::Failed))
})
.await;
draw(&mut self.window);
}
/// The Death Recap of the Match opened is stored or refused.
async fn known(&mut self, cx: &mut TestAppContext) {
cx.condition(&self.page, |p, _| {
matches!(p.matches.death(), Some(Death::Known(_)))
})
.await;
draw(&mut self.window);
}
/// Chooses the Match in `row` of the list, once the one before has settled.
pub(super) async fn open_row(&mut self, cx: &mut TestAppContext, row: usize) {
let at = center(&mut self.window, ROWS[row]);
self.window.simulate_click(at, Modifiers::none());
draw(&mut self.window);
recap_ready(&self.page, cx).await;
self.settled(cx).await;
}
/// Unfolds the player whose Riot ID starts with `name`.
pub(super) fn unfold(&mut self, name: &str) {
let ix = self.page.read_with(&self.window, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.position(|player| player.riot_id.text.starts_with(name))
.unwrap()
});
let at = center(&mut self.window, LINES[ix]);
self.window.simulate_click(at, Modifiers::none());
draw(&mut self.window);
}
/// The Riot ID of the first player of the recap.
fn first_player(&mut self) -> String {
self.page.read_with(&self.window, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
shown.teams[0].players[0].riot_id.text.to_string()
})
}
fn shown_section(&mut self) -> bool {
self.window.debug_bounds("death-recap").is_some()
}
}
/// « Parties » on Alice's Matches, the most recent chosen and its Death Recap settled.
pub(super) async fn open(
cx: &mut TestAppContext,
script: Script,
data: Option<GameData>,
) -> Opened {
cx.executor().allow_parking();
let (script, asked) = (Arc::new(Mutex::new(script)), Arc::default());
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(Timelines {
script,
asked: Arc::clone(&asked),
}),
)
.unwrap()
.with_seasons(Vec::new())
.with_client(Box::new(FakeClient::new("Alice")));
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, None, &mut |_| {});
let named = data.is_some();
let (page, window) = open_page_launched(cx, tracker, None, data);
let mut opened = Opened {
page,
window,
asked,
};
tall(&mut opened.window);
switch_tab(&opened.page, &mut opened.window, Tab::Matches);
if named {
cx.condition(&opened.page, |p, _| !p.matches.catalog().is_empty())
.await;
}
recap_ready(&opened.page, cx).await;
opened.settled(cx).await;
opened
}
fn line(name: &str, total: &str, types: &str) -> (String, String, String) {
(name.into(), total.into(), types.into())
}
fn lines(damage: ShownDamage) -> Vec<(String, String, String)> {
match damage {
ShownDamage::Seen(lines) => lines
.into_iter()
.map(|l| {
(
l.described.name.to_string(),
l.total.to_string(),
l.types.to_string(),
)
})
.collect(),
other => panic!("no lines: {other:?}"),
}
}
#[gpui::test]
async fn each_effect_is_counted_once_for_the_player_who_dealt_it(cx: &mut TestAppContext) {
let dir = TestDir::new("death-recap");
let mut app = open(cx, Script::Serve, Some(cache(&dir))).await;
// The most recent Match was fetched on its first opening; the older one is opened now.
assert_eq!(app.asked(FIRST), 1);
app.open_row(cx, 2).await;
assert_eq!(app.asked(FULL), 1);
// The augment by its `augmentNameId`, the item by the exceptions table, most damaging
// first (180.4 and 120.25 over two kills, rounded after the sum), the rest under
// « Autres effets » (a basic attack, and an effect that is not one of the player's).
assert_eq!(
lines(app.damage_of("Joueur")),
[
line("Renard de feu", "180", "Magiques 180"),
line("Rédemption", "120", "Magiques 120"),
line(OTHERS, "83", "Physiques 50 · Magiques 33"),
]
);
// A champion spell and an effect they do not own: only « Autres effets »; the minion
// that is not a player is nobody's.
assert_eq!(
lines(app.damage_of("Autre01")),
[line(OTHERS, "125", "Magiques 125")]
);
// Nothing dealt in the recaps that were fetched.
assert_eq!(app.damage_of("Autre03"), ShownDamage::Note(NONE_SEEN));
// Drawn for the player unfolded only.
assert!(!app.shown_section());
app.unfold("Joueur");
assert!(app.shown_section());
// Opening them again asks for nothing: stored.
app.open_row(cx, 0).await;
app.open_row(cx, 2).await;
assert_eq!((app.asked(FIRST), app.asked(FULL)), (1, 1));
}
#[gpui::test]
async fn a_refusal_is_unavailable_and_never_asked_again(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Refuse, None).await;
assert_eq!(
app.page
.read_with(&app.window, |p, _| p.matches.death().cloned()),
Some(Death::Known(DeathRecapState::Refused))
);
for player in ["Joueur", "Autre01"] {
assert_eq!(app.damage_of(player), ShownDamage::Note(UNAVAILABLE));
}
app.open_row(cx, 2).await;
app.open_row(cx, 0).await;
app.open_row(cx, 2).await;
assert_eq!((app.asked(FIRST), app.asked(FULL)), (1, 1));
}
#[gpui::test]
async fn a_failure_offers_to_try_again_and_stores_nothing(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Fail(1), None).await;
assert_eq!(
app.page
.read_with(&app.window, |p, _| p.matches.death().cloned()),
Some(Death::Failed)
);
assert_eq!(app.damage_of("Joueur"), ShownDamage::Retry);
// The player's details have the button, and the request is asked once more.
// The first player: the section is on screen without scrolling.
let first = app.first_player();
app.unfold(&first);
assert!(app.window.debug_bounds("death-recap-retry").is_some());
let at = center(&mut app.window, "death-recap-retry");
app.window.simulate_click(at, Modifiers::none());
draw(&mut app.window);
app.known(cx).await;
assert_eq!(app.asked(FIRST), 2);
assert!(matches!(
app.page
.read_with(&app.window, |p, _| p.matches.death().cloned()),
Some(Death::Known(DeathRecapState::Stored(_)))
));
assert!(app.window.debug_bounds("death-recap-retry").is_none());
assert_ne!(app.damage_of("Joueur"), ShownDamage::Retry);
assert_eq!(
app.page.read_with(&app.window, |p, _| p
.matches
.death_fetching()
.map(String::from)),
None
);
}
#[gpui::test]
async fn a_failed_match_is_asked_again_when_opened_again(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Fail(1), None).await;
assert_eq!(app.damage_of("Joueur"), ShownDamage::Retry);
// Another Match, then this one again: nothing was stored.
app.open_row(cx, 2).await;
app.open_row(cx, 0).await;
assert_eq!(app.asked(FIRST), 2);
assert!(matches!(
app.page
.read_with(&app.window, |p, _| p.matches.death().cloned()),
Some(Death::Known(DeathRecapState::Stored(_)))
));
}
#[gpui::test]
async fn the_followers_fetch_shows_in_the_recap_open(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Fail(1), None).await;
assert_eq!(app.damage_of("Joueur"), ShownDamage::Retry);
// The background thread of the queue fetched it meanwhile, and says so.
app.page.update(&mut app.window, |page, _| {
let Recap::Ready { recap, .. } = &page.matches.recap else {
panic!("no recap");
};
page.tracker
.fetch_death_recap(recap, &GameCatalog::default())
.unwrap();
});
app.window.update(|window, cx| {
app.page.update(cx, |page, cx| {
page.apply(Msg::DeathRecapStored(FIRST.into()), window, cx)
})
});
app.known(cx).await;
assert!(!matches!(app.damage_of("Joueur"), ShownDamage::Retry));
// Nobody asked Riot again from the page.
assert_eq!(app.asked(FIRST), 2);
}
#[gpui::test]
async fn a_new_catalog_matches_the_stored_recaps_again(cx: &mut TestAppContext) {
// No names yet: the item still matches by the exceptions table, the augment cannot.
let mut app = open(cx, Script::Serve, None).await;
app.open_row(cx, 2).await;
assert_eq!(
lines(app.damage_of("Joueur")),
[
line("Objet 223107", "120", "Magiques 120"),
line(OTHERS, "263", "Physiques 50 · Magiques 213"),
]
);
let dir = TestDir::new("death-recap-later");
let catalog = Arc::new(cache(&dir).load());
app.window.update(|window, cx| {
app.page.update(cx, |page, cx| {
page.apply(Msg::GameData(catalog), window, cx)
})
});
cx.condition(&app.page, |p, cx| {
p.matches.shown(cx).is_some_and(|shown| {
(shown.teams.iter().flat_map(|t| t.players.iter()))
.any(|player| matches!(&player.damage_seen, ShownDamage::Seen(l) if l.len() == 3))
})
})
.await;
assert_eq!(
lines(app.damage_of("Joueur"))[0],
line("Renard de feu", "180", "Magiques 180")
);
// Nothing more was asked of Riot.
assert_eq!((app.asked(FIRST), app.asked(FULL)), (1, 1));
}
/// The lines of Joueur's damage seen, as many as there are.
fn seen_lines(app: &mut Opened) -> usize {
match app.damage_of("Joueur") {
ShownDamage::Seen(lines) => lines.len(),
other => panic!("no lines: {other:?}"),
}
}
#[gpui::test]
async fn a_death_recap_matched_to_an_old_catalog_is_matched_again(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Serve, None).await;
app.open_row(cx, 2).await;
let dir = TestDir::new("death-recap-stale");
let catalog = Arc::new(cache(&dir).load());
app.window.update(|window, cx| {
app.page.update(cx, |page, cx| {
page.apply(Msg::GameData(catalog), window, cx)
})
});
cx.condition(&app.page, |p, cx| {
p.matches.shown(cx).is_some_and(|shown| {
(shown.teams.iter().flat_map(|t| t.players.iter()))
.any(|player| matches!(&player.damage_seen, ShownDamage::Seen(l) if l.len() == 3))
})
})
.await;
// A read, or a fetch, that began before the game data came lands with the old names.
let stale = app.page.update(&mut app.window, |page, _| {
let Recap::Ready { recap, .. } = &page.matches.recap else {
panic!("no recap");
};
page.tracker
.death_recap(recap, &GameCatalog::default())
.unwrap()
});
app.window.update(|window, cx| {
app.page.update(cx, |page, cx| {
page.apply(
Msg::DeathRecap {
match_id: FULL.into(),
fetched: true,
result: Ok(stale),
catalog: Arc::default(),
},
window,
cx,
)
})
});
assert_eq!(seen_lines(&mut app), 2, "matched to the old names for now");
// Read again with the current catalog: nothing asked of Riot.
cx.condition(&app.page, |p, cx| {
p.matches.shown(cx).is_some_and(|shown| {
(shown.teams.iter().flat_map(|t| t.players.iter()))
.any(|player| matches!(&player.damage_seen, ShownDamage::Seen(l) if l.len() == 3))
})
})
.await;
assert_eq!((app.asked(FIRST), app.asked(FULL)), (1, 1));
}
#[gpui::test]
async fn one_death_recap_read_runs_and_only_the_latest_waits(cx: &mut TestAppContext) {
let mut app = open(cx, Script::Fail(1), None).await;
app.page.update(&mut app.window, |page, cx| {
// Asked again and again while Riot is slow: one read runs, one waits.
for _ in 0..3 {
page.death_recap_stored(FIRST);
}
assert_eq!(page.matches.death_reads(), (true, Some((FIRST, false))));
// « Réessayer » asks Riot; a read of the same Match after it does not undo that.
page.retry_death_recap(cx);
page.death_recap_stored(FIRST);
assert_eq!(page.matches.death_reads(), (true, Some((FIRST, true))));
});
cx.condition(&app.page, |p, _| p.matches.death_reads() == (false, None))
.await;
}
@@ -0,0 +1,268 @@
//! The details a click or a key unfolds under a player of the recap.
use super::key_fixtures::press_key;
use super::matches_fixtures::{ALICE, chosen, open_matches, recap_ready};
use super::page_fixtures::{center, draw, switch_tab};
use crate::page::matches::{ShownPlayer, UNAVAILABLE};
use crate::page::{Page, Tab};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
fn click(cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_click(at, Modifiers::none());
draw(cx);
}
/// The lines of the six players of the fixture.
const LINES: [&str; 6] = [
"recap-player-0",
"recap-player-1",
"recap-player-2",
"recap-player-3",
"recap-player-4",
"recap-player-5",
];
/// The player of the recap shown whose Riot ID starts with `name`, and their index.
fn player(page: &Entity<Page>, cx: &mut VisualTestContext, name: &str) -> (usize, ShownPlayer) {
page.read_with(cx, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.enumerate()
.find(|(_, player)| player.riot_id.text.starts_with(name))
.map(|(ix, player)| (ix, player.clone()))
.unwrap()
})
}
/// The player unfolded.
fn unfolded(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<usize> {
page.read_with(cx, |p, cx| p.matches.unfolded(cx))
}
/// The details of `player` as « title / caption » → text, the missing ones flagged.
fn measure(player: &ShownPlayer, title: &str, caption: &str) -> (String, bool) {
let value = player.details.get(title, caption).unwrap();
(value.text.to_string(), value.missing)
}
/// The fill of the bar of `player`'s measure.
fn bar(player: &ShownPlayer, title: &str, caption: &str) -> Option<f32> {
let group = player.details.0.iter().find(|g| g.title == title).unwrap();
group
.measures
.iter()
.find(|m| m.caption == caption)
.unwrap()
.bar
}
/// Opens the Match with the full recap (the oldest, third in the list).
async fn open_full_recap(
page: &Entity<Page>,
cx: &mut TestAppContext,
window: &mut VisualTestContext,
) {
click(window, "match-row-2");
recap_ready(page, cx).await;
draw(window);
assert_eq!(chosen(page, window).as_deref(), Some(ALICE[2]));
}
#[gpui::test]
async fn the_details_come_from_a_full_recap_as_published(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
let (_, me) = player(&page, &mut window, "Joueur");
let at = |title, caption| measure(&me, title, caption);
// Thousands are grouped with a narrow no-break space; a unit follows after a plain one.
let n = |text: &str| (text.replacen(' ', "\u{202f}", 1), false);
let gold = |text: &str| (format!("{} or", text.replacen(' ', "\u{202f}", 1)), false);
let dealt = "Dégâts aux champions";
assert_eq!(at(dealt, "Total"), n("30 000"));
assert_eq!(at(dealt, "Physiques"), n("12 000"));
assert_eq!(at(dealt, "Magiques"), n("17 000"));
assert_eq!(at(dealt, "Bruts"), n("1 000"));
let taken = "Dégâts reçus";
assert_eq!(at(taken, "Total"), n("20 000"));
assert_eq!(at(taken, "Physiques"), n("9 000"));
assert_eq!(at(taken, "Magiques"), n("10 000"));
assert_eq!(at(taken, "Bruts"), n("1 000"));
assert_eq!(at("Protection", "Dégâts atténués (sur soi)"), n("8 000"));
assert_eq!(at("Protection", "Soins aux alliés"), n("500"));
assert_eq!(at("Protection", "Boucliers sur les alliés"), n("250"));
assert_eq!(at("Or", "Or gagné"), gold("15 000"));
assert_eq!(at("Or", "Or dépensé"), gold("14 000"));
assert_eq!(at("Contrôle", "Contrôle infligé"), ("45 s".into(), false));
assert_eq!(at("Contrôle", "Score de contrôle"), n("20"));
// A published total stays as given, though the types do not add up to it.
let (_, other) = player(&page, &mut window, "Autre04");
assert_eq!(measure(&other, dealt, "Total"), n("31 000"));
// A compared bar is the share of the best of the Match: Autre03 shields 0, the others 250.
let everyone = page.read_with(&window, |p, cx| {
(p.matches.shown(cx).unwrap().teams.iter())
.flat_map(|t| t.players.iter())
.cloned()
.collect::<Vec<_>>()
});
for player in &everyone {
let fill = bar(player, "Protection", "Boucliers sur les alliés").unwrap();
let want = if player.riot_id.text.starts_with("Autre03") {
0.
} else {
1.
};
assert!(
(fill - want).abs() < 1e-6,
"{}: {fill}",
player.riot_id.text
);
}
}
#[gpui::test]
async fn a_missing_field_is_unavailable_and_a_given_zero_is_zero(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
let missing = (UNAVAILABLE.to_string(), true);
let zero = ("0".to_string(), false);
// No physical damage taken, the rest given.
let (_, one) = player(&page, &mut window, "Autre01");
assert_eq!(measure(&one, "Dégâts reçus", "Physiques"), missing);
assert!(!measure(&one, "Dégâts reçus", "Total").1);
// Zero true damage and no shield: the source says 0.
let (_, three) = player(&page, &mut window, "Autre03");
assert_eq!(measure(&three, "Dégâts aux champions", "Bruts"), zero);
assert_eq!(
measure(&three, "Protection", "Boucliers sur les alliés"),
zero
);
// No gold spent, no crowd control time.
let (_, six) = player(&page, &mut window, "Autre06");
assert_eq!(measure(&six, "Or", "Or dépensé"), missing);
assert_eq!(measure(&six, "Contrôle", "Contrôle infligé"), missing);
assert!(!measure(&six, "Or", "Or gagné").1);
// A Match whose payload has no statistics: nothing is 0.
click(&mut window, "match-row-0");
recap_ready(&page, cx).await;
let (_, me) = player(&page, &mut window, "Joueur");
assert!(
me.details
.0
.iter()
.flat_map(|g| &g.measures)
.all(|m| m.value.missing)
);
assert_eq!(measure(&me, "Or", "Or gagné"), missing);
}
#[gpui::test]
async fn a_click_unfolds_a_player_and_another_click_folds_them(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
let cx = &mut window;
// Folded: nothing of the details is built, but each line draws its damage as a bar.
assert_eq!(unfolded(&page, cx), None);
let line = cx.debug_bounds("recap-player-0").unwrap();
let damage = cx.debug_bounds("recap-dealt-0").unwrap();
assert!((damage.center().y - line.center().y).abs() < gpui_kit::px(1.));
assert!(cx.debug_bounds("recap-details").is_none());
let (first, _) = player(&page, cx, "Autre03");
let (second, _) = player(&page, cx, "Joueur");
assert_ne!(first, second);
click(cx, "recap-player-0");
assert_eq!(unfolded(&page, cx), Some(0));
assert!(cx.debug_bounds("recap-details").is_some());
assert!(cx.debug_bounds("recap-split-0").is_some());
// The line stays above its details.
let line = cx.debug_bounds("recap-player-0").unwrap();
assert!(cx.debug_bounds("recap-details").unwrap().top() >= line.bottom());
// Another player: one at a time.
let other = LINES[second];
click(cx, other);
assert_eq!(unfolded(&page, cx), Some(second));
assert!(cx.debug_bounds("recap-details").is_some());
click(cx, other);
assert_eq!(unfolded(&page, cx), None);
assert!(cx.debug_bounds("recap-details").is_none());
assert!(cx.debug_bounds("recap-split-0").is_none());
}
#[gpui::test]
async fn the_keyboard_unfolds_and_folds_without_the_mouse(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
let cx = &mut window;
// The click gives the line the focus; from there, the keys do the rest.
click(cx, "recap-player-1");
assert_eq!(unfolded(&page, cx), Some(1));
press_key(cx, "enter");
assert_eq!(unfolded(&page, cx), None);
assert!(cx.debug_bounds("recap-details").is_none());
press_key(cx, "space");
assert_eq!(unfolded(&page, cx), Some(1));
// Tab reaches « Réessayer » of its Death Recap (the source has no timeline), then the next
// line; Enter unfolds it in place of the first.
press_key(cx, "tab");
press_key(cx, "tab");
press_key(cx, "enter");
assert_eq!(unfolded(&page, cx), Some(2));
press_key(cx, "enter");
assert_eq!(unfolded(&page, cx), None);
}
#[gpui::test]
async fn the_details_are_not_kept_from_one_match_to_another(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
click(&mut window, "recap-player-2");
assert_eq!(unfolded(&page, &mut window), Some(2));
click(&mut window, "match-row-1");
recap_ready(&page, cx).await;
draw(&mut window);
assert_eq!(unfolded(&page, &mut window), None);
assert!(window.debug_bounds("recap-details").is_none());
// Nor from one opening of the screen to the next.
click(&mut window, "recap-player-0");
assert_eq!(unfolded(&page, &mut window), Some(0));
switch_tab(&page, &mut window, Tab::Challenge);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(unfolded(&page, &mut window), None);
}
#[gpui::test]
async fn choosing_a_match_centers_the_displayed_accounts_row(cx: &mut TestAppContext) {
use gpui_kit::{px, size};
let (page, mut window) = open_matches(cx).await;
let banner = window.debug_bounds("banner").unwrap().size.height;
window.simulate_resize(size(px(1280.), banner + px(380.)));
draw(&mut window);
open_full_recap(&page, cx, &mut window).await;
window.run_until_parked();
draw(&mut window);
let row = window.debug_bounds("recap-account").unwrap();
let viewport = window.debug_bounds("recap-viewport").unwrap();
assert!(
(row.center().y - viewport.center().y).abs() < px(1.),
"{row:?} in {viewport:?}"
);
window.simulate_event(gpui_kit::ScrollEvent {
position: viewport.center(),
delta: gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(5000.))),
..Default::default()
});
draw(&mut window);
assert!(window.debug_bounds("recap-account").unwrap().top() > row.top() + px(1.));
click(&mut window, "match-row-2");
window.run_until_parked();
draw(&mut window);
assert!((window.debug_bounds("recap-account").unwrap().top() - row.top()).abs() < px(1.));
assert_eq!(unfolded(&page, &mut window), None);
}
@@ -0,0 +1,317 @@
//! The animation of the end of a Match plays on « Parties » when its end opens the recap there
//! (#110), and on « Défi » otherwise.
use super::banner_fixtures::{banner_champion, banner_statistics, on, ring_ticks};
use super::client_fixtures::FakeClient;
use super::match_end_fixtures::{played, statistics_arrive, until_landed};
use super::matches_auto_open::{before_the_end, its_recap, settle_tabs, tabs};
use super::matches_banner::{dressed, rows};
use super::matches_fixtures::chosen;
use super::matches_provisional::{LEFT_AT_MS, MATCH, block};
use super::page_fixtures::{animations, draw, frame_after, show, switch_tab, tall};
use crate::card_images::tests::TestDir;
use crate::motion::MatchEnd;
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{ChampionState, LastMatch, MatchOutcome, Statistics};
use gpui_kit::{Entity, TestAppContext, VisualTestContext, WindowVisibility};
/// Irelia, whose Match ends, and Ahri validé: before it, and after a top 1 of Irelia's.
fn before(dir: &TestDir) -> Statistics {
banner_statistics(rows(dir), vec![103], None)
}
fn after(dir: &TestDir) -> Statistics {
let mut rows = rows(dir);
rows[0] = banner_champion(39, "Irelia", 3, Some(on(11, 25)), 100);
rows[0].splash = super::matches_banner::rows(dir)[0].splash.clone();
banner_statistics(
rows,
vec![103, 39],
Some(LastMatch {
champion_id: 39,
placement: 1,
outcome: MatchOutcome::Completed(3),
}),
)
}
/// The page on the Défi before Irelia's game ends, under `before`'s statistics.
fn before_the_game(
cx: &mut TestAppContext,
dir: &TestDir,
) -> (Entity<Page>, VisualTestContext, FakeClient) {
let (page, mut window, client, _) = before_the_end(cx);
tall(&mut window);
show(&page, &mut window, before(dir));
draw(&mut window);
(page, window, client)
}
/// The game ends and the follower's round, which brings the end `end` of the Match, stores it
/// and tells the page; the statistics with it arrive.
fn the_game_ends(
page: &Entity<Page>,
client: &FakeClient,
end: MatchEnd,
stats: Statistics,
cx: &mut VisualTestContext,
) {
*client.block.lock().unwrap() = Some(block());
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let snapshot = page.tracker.client_snapshot();
let mut ended = Vec::new();
(page.tracker).follow_client_with(LEFT_AT_MS, None, &snapshot, &mut |_| {}, &mut |m| {
ended.push(m)
});
assert_eq!(ended.len(), 1);
ended[0].end = end;
let status = page.tracker.status();
let msg = Msg::Round {
status,
reload: false,
matches: ended,
game_end: None,
};
page.apply(msg, window, cx);
})
});
statistics_arrive(page, cx, Some(stats));
}
fn playing(page: &Entity<Page>, cx: &mut VisualTestContext) -> bool {
page.read_with(cx, |p, _| p.playback.animation.is_some())
}
fn idle(page: &Entity<Page>, cx: &mut VisualTestContext) -> bool {
page.read_with(cx, |p, _| !p.playback.active() && !p.playback.stats_pending)
}
/// « Défi » as a reload shows it: the ring, the banner and the card of the champion validé.
fn assert_final_challenge(page: &Entity<Page>, cx: &mut VisualTestContext, dir: &TestDir) {
assert!(ring_ticks(page, cx).contains(&(39, ChampionState::Completed)));
page.read_with(cx, |p, cx| {
assert_eq!(
p.banner,
crate::page::home::BannerContent::new(p.home_season.as_ref(), p.home_statistics())
);
let splash = p
.banner_art
.read(cx)
.target
.as_ref()
.map(|s| s.path.clone());
assert_eq!(splash, Some(dir.path().join("Irelia.50.30.jpg")));
assert!(p.home_grid.read(cx).cards().iter().any(|c| c.id == 39));
});
}
#[gpui::test]
async fn the_end_of_a_top_1_plays_on_parties_and_the_challenge_then_shows_its_end_state(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("end-on-matches");
let (page, mut window, client) = before_the_game(cx, &dir);
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
// « Parties » is not shown yet, nor does it hold the Match.
assert!(played(&page, &mut window).is_empty());
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
// The Match is chosen: the comet flies over the banner of « Parties ».
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert!(playing(&page, &mut window));
draw(&mut window);
let renders = |window: &VisualTestContext| {
page.read_with(window, |p, cx| {
let crate::page::matches::Recap::Ready { pane, .. } = &p.matches.recap else {
panic!("recap missing")
};
pane.read(cx).renders
})
};
let before = renders(&window);
assert!(before > 0);
frame_after(&mut window, 16);
assert_eq!(renders(&window), before);
// Under the comet, the champion of the Match before (none); then Irelia's settles in.
assert_eq!(dressed(&page, &mut window), (None, None));
until_landed(&page, &mut window);
assert_eq!(
dressed(&page, &mut window).0.as_deref(),
Some("Irelia.50.30.jpg")
);
for _ in 0..30 {
frame_after(&mut window, 200);
}
assert!(!playing(&page, &mut window) && idle(&page, &mut window));
assert_eq!(
dressed(&page, &mut window),
(Some("Irelia.50.30.jpg".into()), Some(39))
);
// Back on « Défi »: the end state, not played again.
switch_tab(&page, &mut window, Tab::Challenge);
draw(&mut window);
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert!(idle(&page, &mut window) && !playing(&page, &mut window));
assert_final_challenge(&page, &mut window, &dir);
}
#[gpui::test]
async fn leaving_parties_during_the_animation_ends_it_without_a_second_play(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("end-on-matches-left");
let (page, mut window, client) = before_the_game(cx, &dir);
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
assert!(playing(&page, &mut window));
switch_tab(&page, &mut window, Tab::Challenge);
draw(&mut window);
assert!(!playing(&page, &mut window) && idle(&page, &mut window));
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert_final_challenge(&page, &mut window, &dir);
}
#[gpui::test]
async fn it_waits_for_parties_to_show_in_a_hidden_window_or_behind_the_settings(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("end-on-matches-hidden");
let (page, mut window, client) = before_the_game(cx, &dir);
window.update(|window, cx| page.update(cx, |page, cx| page.hidden(window, cx)));
window.simulate_visibility_change(WindowVisibility::Hidden);
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
its_recap(&page, cx).await;
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert_eq!(chosen(&page, &mut window).as_deref(), Some(MATCH));
assert!(played(&page, &mut window).is_empty());
// Shown again, still behind « Paramètres »: nothing yet.
window.simulate_visibility_change(WindowVisibility::Visible);
assert!(played(&page, &mut window).is_empty());
window.update(|window, cx| page.update(cx, |page, cx| page.uncovered(window, cx)));
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert!(playing(&page, &mut window));
}
#[gpui::test]
async fn with_the_preference_off_it_plays_on_the_challenge_and_not_on_parties(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("end-on-challenge");
let (page, mut window, client) = before_the_game(cx, &dir);
page.update(&mut window, |page, _| {
page.set_open_recap_at_match_end(false)
});
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert!(playing(&page, &mut window));
// « Parties » opened by hand plays nothing more.
switch_tab(&page, &mut window, Tab::Matches);
draw(&mut window);
assert_eq!(played(&page, &mut window), [MatchEnd::Completed]);
assert!(idle(&page, &mut window));
}
#[gpui::test]
async fn a_champ_select_that_starts_abandons_the_animation_waiting_on_parties(
cx: &mut TestAppContext,
) {
use arena_tracker_core::ChampSelect;
let dir = TestDir::new("end-on-matches-champ-select");
let (page, mut window, client) = before_the_game(cx, &dir);
window.simulate_visibility_change(WindowVisibility::Hidden);
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
its_recap(&page, cx).await;
assert!(page.read_with(&window, |p, _| p.playback.active()));
let champ_select = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(
Msg::ChampSelect(Some(("Alice#EUW".into(), champ_select))),
window,
cx,
)
})
});
assert!(page.read_with(&window, |p, _| !p.playback.active()));
cx.condition(&page, |p, _| !p.stats_job.running()).await;
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(Msg::ChampSelect(None), window, cx)
})
});
cx.condition(&page, |p, _| !p.stats_job.running()).await;
window.simulate_visibility_change(WindowVisibility::Visible);
draw(&mut window);
assert!(played(&page, &mut window).is_empty());
}
#[gpui::test]
async fn without_animations_nothing_plays_on_parties(cx: &mut TestAppContext) {
let dir = TestDir::new("end-on-matches-still");
let (page, mut window, client) = before_the_game(cx, &dir);
animations(&mut window, false);
the_game_ends(
&page,
&client,
MatchEnd::Completed,
after(&dir),
&mut window,
);
settle_tabs(&page, &mut window);
its_recap(&page, cx).await;
assert_eq!(tabs(&page, &mut window), (Tab::Matches, Tab::Matches));
assert!(played(&page, &mut window).is_empty());
assert!(idle(&page, &mut window));
// The banner is at rest on the Match chosen.
assert_eq!(
dressed(&page, &mut window),
(Some("Irelia.50.30.jpg".into()), Some(39))
);
}
@@ -0,0 +1,340 @@
//! The filters of « Parties »: Season and Format shared with « Statistiques », Placement and the
//! champion search, alone and together.
use super::matches_fixtures::{MORE, chosen, listed, recap_id, recap_ready, tracker_in};
use super::page_fixtures::{
assert_at_rest, center, draw, open_page_with_tracker, show, statistics, switch_tab,
};
use crate::champion_table::tests::row;
use crate::page::matches::Outcome;
use crate::page::{ALL_FORMATS, ALL_SEASONS, Page, Tab};
use arena_tracker_core::{Champion, Date, Format, Season, SeasonScope};
use gpui_kit::component::select::SelectEvent;
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext, px, size};
/// The Season table: « Saison 1 » from 1 Jan. 2026, « Saison 2 » from 1 Sept. 2026, the
/// current one.
fn seasons() -> Vec<Season> {
[("Saison 1", 1), ("Saison 2", 9)]
.map(|(name, month)| Season {
name: name.into(),
start: Date {
year: 2026,
month,
day: 1,
},
official_track: None,
})
.to_vec()
}
/// « Parties » opened on Alice's five Matches, once its list and the recap are there.
async fn open(cx: &mut TestAppContext, seasons: Vec<Season>) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, tracker_in(true, seasons).0);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
(page, window)
}
fn click(cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_click(at, Modifiers::none());
draw(cx);
}
#[derive(Clone, Copy)]
enum Selector {
Season,
Format,
}
/// The player picks `label` in the Season or Format selector, of whichever page shows it.
fn pick(page: &Entity<Page>, cx: &mut VisualTestContext, selector: Selector, label: &str) {
let select = page.read_with(cx, |p, _| match selector {
Selector::Season => p.season_select.clone(),
Selector::Format => p.format_select.clone(),
});
let label = label.to_string();
cx.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some(label.into())))
})
});
draw(cx);
}
/// The player types `text` in the search field of « Parties », whose text is replaced.
fn search(page: &Entity<Page>, cx: &mut VisualTestContext, text: &str) {
let input = page.read_with(cx, |p, _| p.matches.search_input().clone());
cx.update(|window, cx| {
input.update(cx, |input, cx| {
input.focus(window, cx);
input.clean(window, cx);
})
});
if !text.is_empty() {
cx.simulate_input(text);
}
draw(cx);
}
/// The ids of `MORE` at these positions.
fn some(positions: &[usize]) -> Vec<&'static str> {
positions.iter().map(|&ix| MORE[ix]).collect()
}
#[gpui::test]
async fn the_current_season_is_the_default_and_the_list_is_that_seasons(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, seasons()).await;
let cx = &mut window;
page.read_with(cx, |p, cx| {
assert_eq!(p.season, SeasonScope::Season("Saison 2".into()));
let selected = p.season_select.read(cx).selected_value();
assert_eq!(selected.map(|s| s.as_ref()), Some("Saison 2"));
});
assert_eq!(listed(&page, cx), some(&[0, 1, 2]));
// The most recent of them is chosen and its recap shown.
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[0]));
assert_eq!(recap_id(&page, cx).as_deref(), Some(MORE[0]));
for id in [
"matches-season",
"matches-format",
"matches-placement-all",
"matches-placement-top1",
"matches-placement-wins",
] {
assert!(cx.debug_bounds(id).is_some(), "{id}");
}
assert!(cx.debug_bounds("matches-no-result").is_none());
// The filters are above the list, within its column.
let (season, format, rows) = (
cx.debug_bounds("matches-season").unwrap(),
cx.debug_bounds("matches-format").unwrap(),
cx.debug_bounds("match-list").unwrap(),
);
let placement = cx.debug_bounds("matches-placement-all").unwrap();
assert!(season.bottom() <= placement.top() && placement.bottom() <= rows.top());
// Within the list's column (the list's border is 1 px).
assert!(season.right() <= format.left() && format.right() <= rows.right() + px(1.));
assert!(season.left() + px(1.) >= rows.left());
}
#[gpui::test]
async fn without_a_current_season_every_season_is_listed(cx: &mut TestAppContext) {
// The only Season of the table starts in 2099.
let future = Season {
name: "Saison lointaine".into(),
start: Date {
year: 2099,
month: 1,
day: 1,
},
official_track: None,
};
let (page, mut window) = open(cx, vec![future]).await;
let cx = &mut window;
page.read_with(cx, |p, cx| {
assert_eq!(p.season, SeasonScope::AllSeasons);
let selected = p.season_select.read(cx).selected_value();
assert_eq!(selected.map(|s| s.as_ref()), Some(ALL_SEASONS));
});
assert_eq!(listed(&page, cx), MORE);
}
#[gpui::test]
async fn the_season_alone_keeps_the_matches_of_its_period(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, seasons()).await;
let cx = &mut window;
pick(&page, cx, Selector::Season, "Saison 1");
assert_eq!(listed(&page, cx), some(&[3, 4]));
// The Match chosen is not kept: the first one shown is, and its recap follows.
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[3]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, cx).as_deref(), Some(MORE[3]));
pick(&page, cx, Selector::Season, ALL_SEASONS);
assert_eq!(listed(&page, cx), MORE);
// Listed and kept again: the choice stays.
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[3]));
}
#[gpui::test]
async fn the_format_alone_keeps_its_matches(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, Vec::new()).await;
let cx = &mut window;
assert_eq!(listed(&page, cx), MORE);
pick(&page, cx, Selector::Format, &Format::BraveryArena.name());
assert_eq!(listed(&page, cx), some(&[1]));
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[1]));
pick(&page, cx, Selector::Format, &Format::Arena3x6.name());
assert_eq!(listed(&page, cx), some(&[0, 2, 3, 4]));
pick(&page, cx, Selector::Format, ALL_FORMATS);
assert_eq!(listed(&page, cx), MORE);
}
#[gpui::test]
async fn the_placement_alone_keeps_top_1_or_the_wins(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, Vec::new()).await;
let cx = &mut window;
click(cx, "matches-placement-top1");
assert_eq!(listed(&page, cx), some(&[1]));
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[1]));
// A 2nd place is a Win in Arena 3x6, a 5th is not.
click(cx, "matches-placement-wins");
assert_eq!(listed(&page, cx), some(&[0, 1, 2, 4]));
// Listed: the choice stays.
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[1]));
click(cx, "matches-placement-all");
assert_eq!(listed(&page, cx), MORE);
// Each row's Placement is drawn in its outcome's colour.
let outcomes: Vec<Outcome> = page.read_with(cx, |p, cx| {
p.matches
.list
.read(cx)
.rows()
.iter()
.map(|r| r.outcome)
.collect()
});
use Outcome::{Loss, Top1, Win};
assert_eq!(outcomes, [Win, Top1, Win, Loss, Win]);
}
#[gpui::test]
async fn the_search_finds_a_champion_by_name_or_alias(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, Vec::new()).await;
let cx = &mut window;
// No catalog yet: the Match's own name, Riot's key, which the aliases are keyed by.
search(&page, cx, "tf");
assert_eq!(listed(&page, cx), some(&[3]));
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[3]));
search(&page, cx, "IREL");
assert_eq!(listed(&page, cx), some(&[0, 1, 4]));
// The catalog's French name finds it too, and a field emptied lists every Match.
let mut fate = row("Twisted Fate");
fate.champion = Champion {
id: 4,
key: "TwistedFate".into(),
name: "Destin Tordu".into(),
};
show(&page, cx, statistics(0, 1, vec![fate]));
search(&page, cx, "tordu");
assert_eq!(listed(&page, cx), some(&[3]));
page.read_with(cx, |p, cx| {
assert_eq!(p.matches.list.read(cx).rows()[0].champion, "Destin Tordu");
});
search(&page, cx, "");
assert_eq!(listed(&page, cx), MORE);
}
#[gpui::test]
async fn the_filters_combine_and_say_when_nothing_matches(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, seasons()).await;
let cx = &mut window;
assert_eq!(listed(&page, cx), some(&[0, 1, 2]));
click(cx, "matches-placement-wins");
search(&page, cx, "irelia");
assert_eq!(listed(&page, cx), some(&[0, 1]));
click(cx, "matches-placement-top1");
assert_eq!(listed(&page, cx), some(&[1]));
pick(&page, cx, Selector::Format, &Format::BraveryArena.name());
assert_eq!(listed(&page, cx), some(&[1]));
assert!(cx.debug_bounds("matches-no-result").is_none());
// Not in the other Season: nothing is left, the list says so and the recap goes.
pick(&page, cx, Selector::Season, "Saison 1");
assert!(listed(&page, cx).is_empty());
assert_eq!(chosen(&page, cx), None);
assert_eq!(recap_id(&page, cx), None);
assert!(cx.debug_bounds("matches-no-result").is_some());
// The filters stay on screen to be changed.
assert!(cx.debug_bounds("matches-placement-all").is_some());
page.read_with(cx, |p, _| {
assert!(matches!(p.matches.recap, crate::page::matches::Recap::None))
});
// Loosening one brings the Matches, and the first is chosen.
pick(&page, cx, Selector::Season, ALL_SEASONS);
assert_eq!(listed(&page, cx), some(&[1]));
assert!(cx.debug_bounds("matches-no-result").is_none());
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[1]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, cx).as_deref(), Some(MORE[1]));
assert_at_rest(cx);
}
#[gpui::test]
async fn season_and_format_are_the_statistics_pages_and_back(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, seasons()).await;
let cx = &mut window;
let scope = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, _| (p.season.clone(), p.format))
};
// From « Parties » to « Statistiques ».
pick(&page, cx, Selector::Season, "Saison 1");
pick(&page, cx, Selector::Format, &Format::Arena3x6.name());
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
assert_eq!(
scope(&page, cx),
(
SeasonScope::Season("Saison 1".into()),
Some(Format::Arena3x6)
)
);
assert!(cx.debug_bounds("matches-season").is_none());
// From « Statistiques » to « Parties ».
pick(&page, cx, Selector::Season, ALL_SEASONS);
pick(&page, cx, Selector::Format, ALL_FORMATS);
pick(&page, cx, Selector::Format, &Format::BraveryArena.name());
switch_tab(&page, cx, Tab::Matches);
assert_eq!(
scope(&page, cx),
(SeasonScope::AllSeasons, Some(Format::BraveryArena))
);
assert_eq!(listed(&page, cx), some(&[1]));
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[1]));
// Placement and search are not « Statistiques »: it keeps its own.
click(cx, "matches-placement-top1");
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(
page.read_with(cx, |p, _| p.filter),
arena_tracker_core::StateFilter::All
);
}
#[gpui::test]
async fn the_filters_are_with_the_list_in_a_narrow_window(cx: &mut TestAppContext) {
let (page, mut window) = open(cx, Vec::new()).await;
let cx = &mut window;
cx.simulate_resize(size(px(800.), px(700.)));
draw(cx);
assert!(cx.debug_bounds("matches-placement-top1").is_none());
click(cx, "matches-list-toggle");
assert!(cx.debug_bounds("matches-placement-top1").is_some());
click(cx, "matches-placement-top1");
assert_eq!(listed(&page, cx), some(&[1]));
// The filters stay open for another choice: only a Match closes the list.
assert!(cx.debug_bounds("matches-list-over").is_some());
click(cx, "match-row-0");
assert!(cx.debug_bounds("matches-list-over").is_none());
}
#[gpui::test]
async fn the_filters_are_kept_from_one_opening_to_the_next_but_not_the_choice(
cx: &mut TestAppContext,
) {
let (page, mut window) = open(cx, Vec::new()).await;
let cx = &mut window;
click(cx, "matches-placement-wins");
search(&page, cx, "irelia");
assert_eq!(listed(&page, cx), some(&[0, 1, 4]));
click(cx, "match-row-2");
switch_tab(&page, cx, Tab::Challenge);
switch_tab(&page, cx, Tab::Matches);
assert_eq!(listed(&page, cx), some(&[0, 1, 4]));
assert_eq!(chosen(&page, cx).as_deref(), Some(MORE[0]));
}
@@ -0,0 +1,195 @@
use super::client_fixtures::FakeClient;
use super::page_fixtures::{MATCH_1750, draw, open_page_with_tracker, switch_tab, tall};
use crate::page::matches::{Death, Recap};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{Account, MatchHistorySource, Season, SourceError, Tracker};
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
use std::path::Path;
use std::sync::{Arc, Mutex};
/// The Match whose recap has every field: Irelia, 2nd, on 13 May 2026.
pub(super) const RECAP_1750: &str =
include_str!("../../../../core/tests/fixtures/riot/match_1750_recap.json");
/// Alice's Matches, newest first: Irelia on 15 Nov. 2026 (a payload without statistics), Ahri on
/// 21 Sept. 2026, Irelia on 13 May 2026 (the full recap).
pub(super) const ALICE: [&str; 3] = ["EUW1_9000000006", "EUW1_9000000008", "EUW1_9000000007"];
/// Bob's only Match.
pub(super) const BOB: &str = "EUW1_9000000009";
/// Alice's Matches with two more, newest first: `MORE[1]` is Irelia in Bravery Arena on 14 Oct.
/// 2026 (1st), `MORE[3]` Twisted Fate on 29 Aug. 2026 (5th, not a Win); the others are `ALICE`.
pub(super) const MORE: [&str; 5] = [
"EUW1_9000000006",
"EUW1_9000000010",
"EUW1_9000000008",
"EUW1_9000000011",
"EUW1_9000000007",
];
/// Alice and Bob, each with their Arena 3x6 Matches, made from the core's Match-V5 fixtures;
/// `more`: Alice has the two more of `MORE`.
pub(crate) struct TwoAccounts {
pub(crate) more: bool,
}
/// The Match of `json` with the Account ending `placement`th, a Win or not.
fn placed(json: &str, placement: u8, win: bool) -> String {
let (head, account) = json.split_at(json.find("\"puuid\": \"fixture-puuid-self\"").unwrap());
let account = account
.replacen(
"\"placement\": 2,\n \"subteamPlacement\": 2,",
&format!("\"placement\": {placement},\n \"subteamPlacement\": {placement},"),
1,
)
.replacen("\"win\": true", &format!("\"win\": {win}"), 1);
format!("{head}{account}")
}
impl MatchHistorySource for TwoAccounts {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
if queue_id != 1750 || start != 0 {
return Ok(Vec::new());
}
Ok(match puuid {
"Alice" if self.more => MORE.map(String::from).to_vec(),
"Alice" => ALICE.map(String::from).to_vec(),
"Bob" => vec![BOB.into()],
_ => Vec::new(),
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let other = |start: &str| {
MATCH_1750
.replace("EUW1_9000000006", id)
.replace("1794763752767", start)
};
Ok(match id {
"EUW1_9000000006" => MATCH_1750.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000007" => RECAP_1750.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000010" => placed(&other("1792000000000"), 1, true)
.replace("\"queueId\": 1750", "\"queueId\": 1740")
.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000011" => placed(&other("1788000000000"), 5, false)
.replace("\"championId\": 39,", "\"championId\": 4,")
.replace(
"\"championName\": \"Irelia\"",
"\"championName\": \"TwistedFate\"",
)
.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000008" => other("1790000000000")
.replace("\"championId\": 39,", "\"championId\": 103,")
.replace("\"championName\": \"Irelia\"", "\"championName\": \"Ahri\"")
.replace("fixture-puuid-self", "Alice"),
_ => other("1794763752767").replace("fixture-puuid-self", "Bob"),
})
}
}
/// A tracker that knows both Accounts, Alice signed in to the client; the name signs another
/// one in.
pub(super) fn tracker() -> (Tracker, Arc<Mutex<String>>) {
tracker_in(false, Vec::new())
}
/// The same with the Season table `seasons`, and `more` of Alice's Matches.
pub(super) fn tracker_in(more: bool, seasons: Vec<Season>) -> (Tracker, Arc<Mutex<String>>) {
let client = FakeClient::new("Alice");
let tracker = Tracker::open(Path::new(":memory:"), Box::new(TwoAccounts { more }))
.unwrap()
.with_seasons(seasons)
.with_client(Box::new(client.clone()));
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, None, &mut |_| {});
(tracker, client.name)
}
/// « Parties » opened by hand on Alice's Matches, once its list and the recap of the most
/// recent are there.
pub(super) async fn open_matches(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, tracker().0);
tall(&mut window);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
(page, window)
}
/// Waits for the list and the recap of the Match chosen, and for its Death Recap to be asked
/// of Riot (in these fixtures the source has no timeline: « Réessayer »).
pub(super) async fn recap_ready(page: &Entity<Page>, cx: &mut TestAppContext) {
cx.condition(page, |p, _| {
p.matches.entries().is_some()
&& matches!(p.matches.recap, Recap::Ready { .. })
&& p.matches.death() != Some(&Death::Loading)
})
.await;
}
/// The Matches of the list, in its order.
pub(super) fn listed(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<String> {
page.read_with(cx, |p, cx| {
let list = p.matches.list.read(cx);
list.rows().iter().map(|r| r.match_id.clone()).collect()
})
}
/// The Match chosen, as the page and the list have it: they agree.
pub(super) fn chosen(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, cx| {
let selected = p.matches.selected.clone();
assert_eq!(p.matches.list.read(cx).selected(), selected.as_deref());
selected
})
}
/// The Match whose recap is shown.
pub(super) fn recap_id(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, _| match &p.matches.recap {
Recap::Ready { recap, .. } => Some(recap.match_id.clone()),
_ => None,
})
}
/// Bob signs in to the client instead of Alice, and the follower's round says so.
pub(super) fn sign_in_bob(
page: &Entity<Page>,
signed_in: &Mutex<String>,
cx: &mut VisualTestContext,
) {
*signed_in.lock().unwrap() = "Bob".into();
cx.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, "Bob");
page.apply(
Msg::Round {
status,
reload: true,
matches: Vec::new(),
game_end: None,
},
window,
cx,
);
})
});
}
@@ -0,0 +1,159 @@
//! The names and icons of the items and augments in the recap of « Parties ».
use super::matches_fixtures::{ALICE, open_matches, recap_ready, tracker};
use super::page_fixtures::{center, draw, open_page_launched, switch_tab};
use crate::card_images::tests::TestDir;
use crate::page::matches::{ShownPlayer, Slot};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use crate::worker::game_data::fake::FakeCatalog;
use arena_tracker_core::{GameCatalog, GameData};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
use std::sync::Arc;
/// A cache filled from the sources: Rabadon's Deathcap (3089, with its icon) and a named item with
/// none (3020), and the augment 212 with its icon.
pub(super) fn cache(dir: &TestDir) -> GameData {
let data = GameData::new(dir.path().to_owned());
data.refresh(&FakeCatalog::online(), &mut || {}).unwrap();
data
}
/// Opens the Match with the full recap (the oldest, third in the list), items 3157, 3089, 3020
/// and 3340 and augments 101, 212 and 305.
pub(super) async fn open_full_recap(
page: &Entity<Page>,
cx: &mut TestAppContext,
window: &mut VisualTestContext,
) {
// The list is read on a worker: its rows are there once it has arrived.
cx.condition(page, |p, _| p.matches.entries().is_some())
.await;
draw(window);
let at = center(window, "match-row-2");
window.simulate_click(at, Modifiers::none());
draw(window);
recap_ready(page, cx).await;
draw(window);
}
fn account(page: &Entity<Page>, cx: &mut VisualTestContext) -> ShownPlayer {
page.read_with(cx, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.is_account)
.unwrap()
.clone()
})
}
fn title_and_icon(slot: &Slot) -> (String, bool) {
match slot {
Slot::Item(item) => (item.name.to_string(), item.icon.is_some()),
other => panic!("not an item: {other:?}"),
}
}
fn names(player: &ShownPlayer) -> Vec<(String, bool)> {
player
.augments
.as_ref()
.unwrap()
.iter()
.map(|a| (a.name.to_string(), a.icon.is_some()))
.collect()
}
fn assert_known_names(player: &ShownPlayer) {
let items = player.items.as_ref().unwrap();
assert_eq!(title_and_icon(&items[0]), ("Objet 3157".into(), false));
assert_eq!(
title_and_icon(&items[1]),
("Coiffe de Rabadon".into(), true)
);
assert_eq!(items[2], Slot::Empty);
// Named, without an icon in the cache: the neutral one.
assert_eq!(
title_and_icon(&items[3]),
("Bottes de sorcier".into(), false)
);
assert_eq!(
names(player),
[
("Amélioration 101".to_string(), false),
("Adaptation".to_string(), true),
("Amélioration 305".to_string(), false),
]
);
}
#[gpui::test]
async fn known_ids_show_their_names_and_icons_and_unknown_ones_the_neutral_look(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("recap-game-data");
let data = cache(&dir);
let (page, mut window) = open_page_launched(cx, tracker().0, None, Some(data));
switch_tab(&page, &mut window, Tab::Matches);
// The cache is read at launch, on a worker.
cx.condition(&page, |p, _| !p.matches.catalog().is_empty())
.await;
open_full_recap(&page, cx, &mut window).await;
assert_known_names(&account(&page, &mut window));
}
#[gpui::test]
async fn a_new_catalog_writes_the_recap_shown_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
// No cache yet: today's look.
let me = account(&page, &mut window);
let items = me.items.as_ref().unwrap();
assert_eq!(title_and_icon(&items[1]), ("Objet 3089".into(), false));
assert_eq!(names(&me)[1], ("Amélioration 212".to_string(), false));
let dir = TestDir::new("recap-game-data-later");
let catalog: Arc<GameCatalog> = Arc::new(cache(&dir).load());
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(Msg::GameData(catalog), window, cx)
})
});
// The same recap, the same Match, new names.
assert_known_names(&account(&page, &mut window));
assert_eq!(
page.read_with(&window, |p, _| p.matches.selected.clone())
.as_deref(),
Some(ALICE[2])
);
}
#[gpui::test]
async fn the_icons_are_loaded_for_the_recap_and_go_with_the_screen(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("recap-game-icons");
let data = cache(&dir);
let (page, mut window) = open_page_launched(cx, tracker().0, None, Some(data));
switch_tab(&page, &mut window, Tab::Matches);
cx.condition(&page, |p, _| !p.matches.catalog().is_empty())
.await;
open_full_recap(&page, cx, &mut window).await;
window.run_until_parked();
draw(&mut window);
let images = page.read_with(&window, |p, cx| p.matches.recap_images(cx));
let held = images.read_with(&window, |images, _| images.held());
let names: Vec<_> = held
.iter()
.filter_map(|path| path.file_name()?.to_str())
.collect();
assert!(names.contains(&"3089.png"), "{names:?}");
assert!(names.contains(&"212.png"), "{names:?}");
switch_tab(&page, &mut window, Tab::Challenge);
assert!(
images
.read_with(&window, |images, _| images.held())
.is_empty()
);
}
@@ -0,0 +1,252 @@
//! A Provisional Match in « Parties »: its badge and its « En attente », and its publication
//! replacing it with the selection and the unfolded player kept.
use super::client_fixtures::FakeClient;
use super::matches_fixtures::{TwoAccounts, recap_ready};
use super::page_fixtures::{center, draw, open_page_with_tracker, switch_tab, tall};
use crate::page::matches::{AWAITED, Recap, ShownDamage};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{
Account, EndOfGameBlock, MatchHistorySource, Season, SourceError, Tracker,
};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
use serde_json::json;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// The game of the Provisional Match, and its Match once Riot publishes it.
pub(super) const GAME: u64 = 9_000_000_020;
pub(super) const MATCH: &str = "EUW1_9000000020";
/// When the player left the game: after every Match of the fixtures.
pub(crate) const LEFT_AT_MS: i64 = 1_795_000_000_000;
const RETRY_MS: i64 = 20_000;
/// Alice's history, which publishes the Match of the game once `published`.
struct Publishing {
published: Arc<AtomicBool>,
}
impl MatchHistorySource for Publishing {
fn resolve_account(&self, name: &str, tag: &str) -> Result<Account, SourceError> {
TwoAccounts { more: false }.resolve_account(name, tag)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
since: Option<i64>,
) -> Result<Vec<String>, SourceError> {
TwoAccounts { more: false }.match_ids(puuid, queue_id, start, count, since)
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
if id != MATCH {
return TwoAccounts { more: false }.fetch_match(id);
}
if !self.published.load(Ordering::SeqCst) {
return Err(SourceError::NotFound);
}
Ok(super::page_fixtures::MATCH_1750
.replace("EUW1_9000000006", MATCH)
.replace("fixture-puuid-self", "Alice"))
}
}
/// The block of the game: Alice (Irelia) third, among 18 players in 6 teams of 3.
pub(crate) fn block() -> EndOfGameBlock {
let standing = [3, 1, 2, 4, 5, 6];
let players: Vec<_> = (0..18u32)
.map(|i| {
let mine = i == 0;
json!({
"puuid": if mine { "client-alice".to_string() } else { format!("client-{i}") },
"riotIdGameName": if mine { "Alice".to_string() } else { format!("Autre{i}") },
"riotIdTagLine": "EUW",
"championId": if mine { 39 } else { 500 + i },
"subteamId": i / 3 + 1,
"subteamStanding": standing[(i / 3) as usize],
"level": 15,
"kills": i,
"deaths": 2,
"assists": 3,
"items": [3089, 0, 0, 0, 0, 0, 3340],
"augments": [1, 2, 3],
"totalDamageDealtToChampions": 1000 * (i + 1),
})
})
.collect();
let content = json!({
"gameId": GAME,
"gameMode": "CHERRY",
"queueId": 1750,
"gameLength": 1200,
"statsBlock": {"players": players},
});
EndOfGameBlock {
content: content.to_string(),
client_puuid: Some("client-alice".into()),
signed_in_riot_id: Some("Alice#EUW".into()),
}
}
/// A tracker on the Season table `seasons` following Alice in her lobby before the game ends,
/// the switch that publishes its Match and Alice's client, which holds the game's block.
pub(crate) fn tracker_before_block(seasons: Vec<Season>) -> (Tracker, Arc<AtomicBool>, FakeClient) {
let published = Arc::new(AtomicBool::new(false));
let client = FakeClient::new("Alice");
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(Publishing {
published: published.clone(),
}),
)
.unwrap()
.with_seasons(seasons)
.with_client(Box::new(client.clone()));
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, None, &mut |_| {});
(tracker, published, client)
}
/// A tracker whose Provisional Match is stored, and the switch that publishes it.
fn tracker_with_provisional() -> (Tracker, Arc<AtomicBool>) {
let (tracker, published, client) = tracker_before_block(Vec::new());
*client.block.lock().unwrap() = Some(block());
tracker.follow_client(LEFT_AT_MS, None, &mut |_| {});
let stored = tracker.matches("Alice").unwrap();
assert!(stored.iter().any(|m| m.match_id == MATCH && m.provisional));
(tracker, published)
}
fn is_provisional(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<bool> {
page.read_with(cx, |p, _| match &p.matches.recap {
Recap::Ready { recap, .. } => Some(recap.provisional),
_ => None,
})
}
#[gpui::test]
async fn a_provisional_match_has_its_badge_and_waits_for_its_values(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (tracker, _) = tracker_with_provisional();
let (page, mut window) = open_page_with_tracker(cx, tracker);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
let (first, selected) = page.read_with(&window, |p, cx| {
let rows = p.matches.list.read(cx).rows().to_vec();
(rows[0].clone(), p.matches.selected.clone())
});
assert_eq!(first.match_id, MATCH);
assert!(first.provisional);
assert_eq!(selected.as_deref(), Some(MATCH));
// In the recap header too.
assert!(window.debug_bounds("recap-provisional").is_some());
// No damage types yet: each line's bar keeps its length, in one colour.
assert!(window.debug_bounds("recap-dealt-plain").is_some());
page.read_with(&window, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
assert!(shown.provisional);
assert_eq!(p.matches.death_fetching(), None);
// What the block does not give is waited for, never « Indisponible ».
let mut missing = Vec::new();
for team in &shown.teams {
missing.extend(team.placement.missing.then_some(&team.placement));
for player in &team.players {
missing.extend([&player.riot_id, &player.level]);
// No timeline yet: waited for too, and not asked for.
assert_eq!(player.damage_seen, ShownDamage::Note(AWAITED));
for group in &player.details.0 {
missing.extend(group.measures.iter().map(|m| &m.value));
}
}
}
let missing: Vec<_> = missing.into_iter().filter(|v| v.missing).collect();
assert!(!missing.is_empty());
assert!(missing.iter().all(|v| v.text == AWAITED), "{missing:?}");
});
}
#[gpui::test]
async fn publication_replaces_the_provisional_match_keeping_the_selection_and_the_player_open(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let (tracker, published) = tracker_with_provisional();
let (page, mut window) = open_page_with_tracker(cx, tracker);
tall(&mut window);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
assert_eq!(is_provisional(&page, &mut window), Some(true));
// Alice's line is unfolded: third, her team is the third.
let alice = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
let shown = p.matches.shown(cx).unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter())).position(|p| p.is_account)
})
};
let line = alice(&page, &mut window).unwrap();
assert_eq!(line, 6);
let at = center(&mut window, "recap-player-6");
window.simulate_click(at, Modifiers::none());
draw(&mut window);
let open = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| p.matches.unfolded(cx))
};
assert_eq!(open(&page, &mut window), Some(6));
// Riot publishes the Match: the follower's round stores it and tells the page.
published.store(true, Ordering::SeqCst);
window.update(|window, cx| {
page.update(cx, |page, cx| {
let changed = page
.tracker
.follow_client(LEFT_AT_MS + 3 * RETRY_MS, None, &mut |_| {});
assert!(changed, "the round says stored data changed");
let status = page.tracker.status();
page.apply(
Msg::Round {
status,
reload: true,
matches: Vec::new(),
game_end: None,
},
window,
cx,
);
})
});
cx.condition(
&page,
|p, _| matches!(&p.matches.recap, Recap::Ready { recap, .. } if !recap.provisional),
)
.await;
draw(&mut window);
page.read_with(&window, |p, cx| {
// No switch: the same Match stays chosen, as a published one.
assert_eq!(p.matches.selected.as_deref(), Some(MATCH));
let rows = p.matches.list.read(cx).rows().to_vec();
assert_eq!(rows[0].match_id, MATCH);
assert!(!rows[0].provisional);
assert_eq!(rows.iter().filter(|r| r.match_id == MATCH).count(), 1);
// The published values: Riot's Placement (2nd), nothing waited for.
let shown = p.matches.shown(cx).unwrap();
assert!(!shown.provisional);
let account = shown.teams.iter().find(|t| t.account).unwrap();
assert_eq!(account.placement.text, "2ᵉ");
assert!(shown.teams.iter().all(|t| t.placement.text != AWAITED));
});
assert!(window.debug_bounds("recap-provisional").is_none());
// Second now, Alice moved up a team: her details followed her.
let moved = alice(&page, &mut window);
assert_ne!(moved, Some(6));
assert_eq!(open(&page, &mut window), moved);
}
@@ -0,0 +1,111 @@
//! When « Parties » reads again: a list is not read again for nothing, and a recap that failed
//! is decoded again.
use super::matches_fixtures::{ALICE, open_matches, recap_id, recap_ready};
use super::page_fixtures::switch_tab;
use crate::page::Tab;
use crate::page::matches::Recap;
use crate::worker::Msg;
use gpui_kit::TestAppContext;
use std::sync::Arc;
// The list's `generation` counts the reads asked for: leaving adds one (what is being read is
// dropped), and each reading asked for another.
#[gpui::test]
async fn the_list_is_not_read_again_when_nothing_changed_while_the_screen_was_hidden(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let before = page.read_with(&window, |p, _| p.matches.generation());
switch_tab(&page, &mut window, Tab::Challenge);
switch_tab(&page, &mut window, Tab::Matches);
// No read of the list; the most recent Match is chosen again from the list kept.
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 1
);
assert_eq!(
page.read_with(&window, |p, _| p.matches.selected.clone())
.as_deref(),
Some(ALICE[0])
);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn stored_data_changing_while_hidden_reads_the_list_at_the_next_opening(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let before = page.read_with(&window, |p, _| p.matches.generation());
switch_tab(&page, &mut window, Tab::Challenge);
window.update(|window, cx| page.update(cx, |page, cx| page.apply(Msg::Champions, window, cx)));
// Hidden: only marked.
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 1
);
switch_tab(&page, &mut window, Tab::Matches);
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 2
);
recap_ready(&page, cx).await;
}
#[gpui::test]
async fn a_list_cut_short_by_leaving_is_read_again_at_the_next_opening(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
window.update(|window, cx| {
page.update(cx, |page, cx| {
let before = page.matches.generation();
// A read is running as the screen leaves: its result is dropped.
page.apply(Msg::Champions, window, cx);
page.close_matches(window, cx);
assert_eq!(page.matches.generation(), before + 2);
page.open_matches(cx);
assert_eq!(page.matches.generation(), before + 3);
})
});
}
/// The recap of the Match chosen fails to decode.
fn fail(page: &gpui_kit::Entity<crate::page::Page>, cx: &mut gpui_kit::VisualTestContext) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let generation = page.matches.recap_generation();
page.apply(
Msg::Recap {
generation,
recap: Box::new(Err("base verrouillée".into())),
death: Box::new(Ok(arena_tracker_core::DeathRecapState::NotFetched)),
catalog: Arc::default(),
},
window,
cx,
);
assert!(matches!(page.matches.recap, Recap::Failed(_)));
})
});
}
#[gpui::test]
async fn a_recap_that_failed_is_decoded_again_when_the_list_is_read_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
fail(&page, &mut window);
window.update(|window, cx| page.update(cx, |page, cx| page.apply(Msg::Champions, window, cx)));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn a_recap_that_failed_is_decoded_again_when_the_screen_opens_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
fail(&page, &mut window);
switch_tab(&page, &mut window, Tab::Challenge);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
+56 -26
View File
@@ -1,51 +1,81 @@
use super::key_fixtures::press_key;
use super::page_fixtures::{
animations, assert_at_rest, center, champions, draw, frame_after, open_page,
open_page_in_season, show, shown_tab, start_switch, statistics, switch_tab, veil,
};
use crate::page::Tab;
use gpui_kit::{
KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext, VisualTestContext,
WindowVisibility,
};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, WindowVisibility};
/// Tab moves the focus `count` elements on, then Enter activates the one reached.
fn tab_then_enter(cx: &mut VisualTestContext, count: usize) {
cx.update(|window, cx| {
for _ in 0..count {
window.focus_next(cx);
}
});
draw(cx);
press_key(cx, "enter");
}
#[gpui::test]
fn the_navigation_switches_tabs_with_the_mouse(cx: &mut TestAppContext) {
fn the_top_bar_has_no_statistics_tab(cx: &mut TestAppContext) {
let (_page, cx) = open_page(cx);
let cx = &mut { cx };
draw(cx);
assert!(cx.debug_bounds("tab-challenge").is_some());
assert!(cx.debug_bounds("tab-statistics").is_none());
}
#[gpui::test]
fn the_banner_link_opens_the_page_and_the_back_button_returns_with_the_mouse(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab);
cx.update(|window, cx| window.draw(cx).clear(cx));
draw(cx);
assert_eq!(tab(cx), Tab::Challenge);
assert!(cx.debug_bounds("back-to-challenge").is_none());
let statistics = center(cx, "tab-statistics");
cx.simulate_click(statistics, Modifiers::none());
let link = center(cx, "statistics-link");
cx.simulate_click(link, Modifiers::none());
assert_eq!(tab(cx), Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
// The same veil as any switch: the page is shown once it covers the screen.
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
assert!(cx.debug_bounds("statistics-link").is_none());
let back = center(cx, "back-to-challenge");
cx.simulate_click(back, Modifiers::none());
assert_eq!(tab(cx), Tab::Challenge);
switch_tab(&page, cx, Tab::Challenge);
draw(cx);
// « Défi » stays in the top bar on « Statistiques », and takes back too.
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
let challenge = center(cx, "tab-challenge");
cx.simulate_click(challenge, Modifiers::none());
assert_eq!(tab(cx), Tab::Challenge);
}
#[gpui::test]
fn the_navigation_switches_tabs_with_the_keyboard(cx: &mut TestAppContext) {
fn the_banner_link_and_the_back_button_work_with_the_keyboard(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
cx.update(|window, cx| window.draw(cx).clear(cx));
// Tab reaches « Défi » first, then « Statistiques ».
cx.update(|window, cx| {
window.focus_next(cx);
window.focus_next(cx);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert_eq!(page.read_with(cx, |page, _| page.tab), Tab::Statistics);
let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab);
draw(cx);
// Tab reaches « Défi », « Parties », then the account selector, then « Statistiques » in
// the banner.
tab_then_enter(cx, 4);
assert_eq!(tab(cx), Tab::Statistics);
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
// On the page, « Défi », « Parties », the selector, then « ‹ Défi ».
tab_then_enter(cx, 4);
assert_eq!(tab(cx), Tab::Challenge);
}
#[gpui::test]
+27 -101
View File
@@ -1,11 +1,10 @@
use crate::card_grid::CardGrid;
use crate::champion_table::tests::row;
use crate::motion::MatchEnd;
use crate::page::{Page, Tab};
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
ChampionState, Charts, Date, FollowedMatch, Format, MatchHistorySource, RiotApi, Season,
SourceError, Statistics, Status, Tracker,
ChampionState, Charts, Date, Format, GameData, MatchHistorySource, RiotApi, Season,
SourceError, Statistics, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
@@ -18,11 +17,11 @@ use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
pub(super) const MATCH_1750: &str =
pub(crate) const MATCH_1750: &str =
include_str!("../../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json");
/// Switches to a tab, and lets its transition end.
pub(super) fn switch_tab(page: &Entity<Page>, cx: &mut VisualTestContext, tab: Tab) {
pub(in crate::page) fn switch_tab(page: &Entity<Page>, cx: &mut VisualTestContext, tab: Tab) {
cx.update(|window, cx| page.update(cx, |page, cx| page.set_tab(tab, window, cx)));
for _ in 0..10 {
if page.read_with(cx, |page, _| page.fade.is_none()) {
@@ -45,7 +44,7 @@ pub(super) fn open_page(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestCon
)
}
pub(super) fn open_page_with_tracker(
pub(crate) fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<Page>, VisualTestContext) {
@@ -57,12 +56,26 @@ pub(super) fn open_page_with_sort(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
) -> (Entity<Page>, VisualTestContext) {
open_page_launched(cx, tracker, champion_sort, None)
}
/// `game_data`: the cache of the items' and augments' names and icons.
pub(super) fn open_page_launched(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
game_data: Option<GameData>,
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
cx.update(crate::page::init);
let tracker = Arc::new(tracker);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
if let Some(data) = game_data {
crate::worker::game_data::fake::spawn_game_catalog(data, tx.clone());
}
let bounds = Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
@@ -79,6 +92,7 @@ pub(super) fn open_page_with_sort(
notice: None,
following: false,
champion_sort,
open_recap_at_match_end: true,
},
rx,
tx,
@@ -227,7 +241,13 @@ pub(super) fn grid_names(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) ->
})
}
pub(super) fn draw(cx: &mut VisualTestContext) {
/// The window as tall as « Parties » needs to show a whole recap under the banner (#110).
pub(super) fn tall(cx: &mut VisualTestContext) {
cx.simulate_resize(size(px(1280.), px(1500.)));
draw(cx);
}
pub(crate) fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
@@ -380,100 +400,6 @@ pub(super) fn start_switch(page: &Entity<Page>, cx: &mut VisualTestContext, tab:
draw(cx);
}
/// A follower round reports Matches of the viewed Account, as (champion, what it brought,
/// start), the way the follower does.
pub(super) fn round_with_matches(
page: &Entity<Page>,
cx: &mut VisualTestContext,
matches: &[(u32, MatchEnd, i64)],
) {
use crate::worker::Msg;
let matches = matches
.iter()
.map(|&(champion_id, end, started_at_ms)| FollowedMatch {
puuid: "p".into(),
season: "Saison".into(),
champion_id,
started_at_ms,
end,
})
.collect();
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = Status {
updating: Some(Account {
puuid: "p".into(),
game_name: "Alice".into(),
tag_line: "EUW".into(),
}),
..page.status.clone()
};
page.apply(
Msg::Round {
status,
reload: false,
matches,
},
window,
cx,
)
})
});
}
/// The statistics job the round started ends with `stats`, else with those shown.
pub(super) fn statistics_arrive(
page: &Entity<Page>,
cx: &mut VisualTestContext,
stats: Option<Statistics>,
) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let stats = stats
.or_else(|| page.stats.clone())
.unwrap_or_else(|| statistics(0, 5, champions(5)));
page.apply(
crate::worker::Msg::Statistics {
generation: page.stats_generation,
stats: Ok(stats),
home: None,
stored: Some(1),
},
window,
cx,
)
})
});
}
/// The end of a followed Match with champion 1, through the round and the statistics.
pub(super) fn animate(page: &Entity<Page>, cx: &mut VisualTestContext, end: MatchEnd) {
round_with_matches(page, cx, &[(1, end, 0)]);
statistics_arrive(page, cx, None);
}
pub(super) fn played(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<MatchEnd> {
page.read_with(cx, |page, _| page.played.clone())
}
pub(super) fn home_names(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<gpui_kit::SharedString> {
page.read_with(cx, |p, cx| p.home_grid.read(cx).names())
}
/// Frames until the comet of the animation playing lands.
pub(super) fn until_landed(page: &Entity<Page>, cx: &mut VisualTestContext) {
for _ in 0..20 {
frame_after(cx, 100);
if page.read_with(cx, |p, _| p.playback.previous_banner.is_none()) {
return;
}
}
panic!("the comet never landed");
}
/// Nothing is drawn at rest: once gpui-kit's own short animations are over (the filters'
/// pill arrives with « Statistiques »), no frame is asked for.
pub(super) fn assert_at_rest(cx: &mut VisualTestContext) {
+12 -1
View File
@@ -170,7 +170,7 @@ async fn a_grid_that_is_not_shown_gives_its_portraits_back(cx: &mut TestAppConte
keys.len()
);
// A champ select takes the home's place with its own sections.
// A champ select shows « Sélection », with its own sections.
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
load(&mut window);
@@ -178,6 +178,17 @@ async fn a_grid_that_is_not_shown_gives_its_portraits_back(cx: &mut TestAppConte
let anvil = page.read_with(&window, |p, _| p.anvil_grid.clone());
assert_eq!(held(&anvil, &mut window), ANVIL.len());
// « Défi » during the champ select shows the home's cards, and « Sélection » gives its own
// back; going back to it, they load again.
switch_tab(&page, &mut window, Tab::Challenge);
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
assert_eq!(held(&anvil, &mut window), 0);
switch_tab(&page, &mut window, Tab::ChampSelect);
load(&mut window);
assert_eq!(held(&home, &mut window), 0);
assert_eq!(held(&anvil, &mut window), ANVIL.len());
// And gives the Anvil row up when it ends.
leave(&page, &mut window);
assert_eq!(held(&anvil, &mut window), 0);
+298
View File
@@ -0,0 +1,298 @@
//! The ring under the pointer (#112): it aims at a tick by angle, lights it and has the banner
//! present its champion, back to the screen's rest state once the pointer leaves the crown.
use super::banner_fixtures::{
banner_champion, banner_rows, banner_statistics, draw_loaded, held_splashes, last_match_of,
ring_renders, ring_ticks, splash,
};
use super::match_end_fixtures::animate;
use super::page_fixtures::{animations, draw, frame_after, open_page_in_season, show, statistics};
use crate::card_images::tests::TestDir;
use crate::motion::MatchEnd;
use crate::page::Page;
use crate::ring::tests::{on_crown, tick_centre};
use arena_tracker_core::{ChampionRow, Statistics};
use std::cell::Cell;
use std::rc::Rc;
use gpui_kit::{Entity, Modifiers, Pixels, Point, TestAppContext, VisualTestContext, point, px};
/// Brand then Ahri Completed, Garen then Zyra played, Lux never played: the ring's order. Each
/// has a splash; Brand took 1 Attempt, Ahri 3; Garen's best Placement is 3ᵉ, Zyra's unknown.
fn rows(dir: &std::path::Path) -> Vec<ChampionRow> {
let mut rows = banner_rows();
for row in &mut rows {
row.splash = Some(splash(dir, &row.champion.name));
}
rows[0].attempts = Some(3);
rows[1].attempts = Some(1);
rows[2].challenge.as_mut().unwrap().best_placement = Some(3);
rows[4] = banner_champion(3, "Zyra", 1, None, 50);
rows[4].splash = Some(splash(dir, "Zyra"));
rows
}
fn challenge(dir: &std::path::Path) -> Statistics {
banner_statistics(rows(dir), vec![2, 1], last_match_of(1))
}
/// Where the middle of tick `index` is, in the window.
fn tick_at(page: &Entity<Page>, cx: &mut VisualTestContext, index: usize) -> Point<Pixels> {
let ring = cx.debug_bounds("ring").unwrap();
ring.origin + tick_centre(index, ring_ticks(page, cx).len(), ring.size)
}
/// The pointer on the middle of tick `index`.
fn aim(page: &Entity<Page>, cx: &mut VisualTestContext, index: usize) {
let at = tick_at(page, cx, index);
move_to(cx, at);
}
fn move_to(cx: &mut VisualTestContext, at: Point<Pixels>) {
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
}
fn lit(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<u32> {
page.read_with(cx, |p, cx| p.ring.read(cx).lit())
}
/// The first line the banner shows for the champion aimed at, none at rest.
fn line(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, _| {
(p.ring_hover.aimed.as_ref()).map(|aimed| aimed.line.text.to_string())
})
}
/// The file of the splash the banner's illustration is going to show.
fn art(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, cx| {
let target = p.banner_art.read(cx).target.clone();
target.map(|s| s.path.file_name().unwrap().to_string_lossy().into_owned())
})
}
#[gpui::test]
fn aiming_the_ring_lights_the_tick_and_presents_its_champion_until_the_pointer_leaves(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("ring-hover");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, challenge(dir.path()));
draw(cx);
assert_eq!(ring_ticks(&page, cx).len(), 5);
let banner = cx.debug_bounds("banner").unwrap();
// At rest: the last Match's champion, no tick lit.
assert_eq!((lit(&page, cx), line(&page, cx)), (None, None));
assert_eq!(art(&page, cx).as_deref(), Some("Ahri.50.30.jpg"));
// Completed in 1 Attempt, then in 3: the second tick, a third of the way round, is Ahri's.
aim(&page, cx, 0);
assert_eq!(lit(&page, cx), Some(2));
assert_eq!(
line(&page, cx).as_deref(),
Some("Brand · validé le 3 nov. · du premier coup")
);
assert_eq!(art(&page, cx).as_deref(), Some("Brand.50.30.jpg"));
aim(&page, cx, 1);
assert_eq!(lit(&page, cx), Some(1));
assert_eq!(
line(&page, cx).as_deref(),
Some("Ahri · validé le 20 nov. · 3 Tentatives")
);
assert_eq!(art(&page, cx).as_deref(), Some("Ahri.50.30.jpg"));
// Played: its Matches and best Placement, then without a Placement, then a single Match.
aim(&page, cx, 2);
assert_eq!(
line(&page, cx).as_deref(),
Some("Garen · 2 Parties · meilleur Placement 3ᵉ")
);
aim(&page, cx, 3);
assert_eq!(line(&page, cx).as_deref(), Some("Zyra · 1 Partie"));
aim(&page, cx, 4);
assert_eq!(line(&page, cx).as_deref(), Some("Lux · jamais joué"));
assert_eq!(art(&page, cx).as_deref(), Some("Lux.50.30.jpg"));
// Nothing of the banner moved.
assert_eq!(cx.debug_bounds("banner"), Some(banner));
// The middle of the ring is not the crown: back to rest.
let ring = cx.debug_bounds("ring").unwrap();
move_to(cx, ring.center());
assert_eq!((lit(&page, cx), line(&page, cx)), (None, None));
assert_eq!(art(&page, cx).as_deref(), Some("Ahri.50.30.jpg"));
// Aimed again, then the pointer leaves the ring for the page.
aim(&page, cx, 4);
assert_eq!(lit(&page, cx), Some(5));
move_to(cx, point(px(5.), px(5.)));
assert_eq!((lit(&page, cx), line(&page, cx)), (None, None));
assert_eq!(art(&page, cx).as_deref(), Some("Ahri.50.30.jpg"));
}
// Rule #1: the ring is drawn again only for a new tick, and nothing is done off the crown.
#[gpui::test]
fn nothing_is_drawn_again_until_the_aimed_tick_changes(cx: &mut TestAppContext) {
let dir = TestDir::new("ring-hover-light");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, challenge(dir.path()));
draw(cx);
let renders = ring_renders(&page, cx);
aim(&page, cx, 1);
assert_eq!(ring_renders(&page, cx), renders + 1);
// The page is told of nothing more.
let notified = Rc::new(Cell::new(0));
let counted = notified.clone();
cx.update(|_, cx| {
cx.observe(&page, move |_, _| counted.set(counted.get() + 1))
.detach()
});
// Elsewhere in the same tick's sector, on the crown or not quite: no change, no frame.
let ring = cx.debug_bounds("ring").unwrap();
for (degrees, radius) in [(80., 230.), (90., 205.), (100., 250.)] {
cx.simulate_mouse_move(
ring.origin + on_crown(degrees, radius, ring.size),
None,
Modifiers::none(),
);
assert_eq!(notified.get(), 0, "{degrees}");
}
assert_eq!(ring_renders(&page, cx), renders + 1);
// Off the crown, inside the ring's square or out of it: the tick goes out, once.
move_to(cx, ring.center());
assert_eq!(ring_renders(&page, cx), renders + 2);
for at in [
ring.center(),
ring.origin + point(px(1.), px(1.)),
point(px(5.), px(5.)),
] {
cx.simulate_mouse_move(at, None, Modifiers::none());
}
// Told once, of the tick going out.
assert_eq!(notified.get(), 1);
assert_eq!(ring_renders(&page, cx), renders + 2);
}
// A quick sweep of the crown asks for many illustrations and decodes the first and the last.
#[gpui::test]
fn a_sweep_holds_two_splashes_at_most_and_ends_on_the_last_aimed(cx: &mut TestAppContext) {
let dir = TestDir::new("ring-hover-sweep");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, challenge(dir.path()));
draw_loaded(cx);
let loads = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| p.banner_art.read(cx).loads)
};
let before = loads(&page, cx);
for index in [0, 2, 4, 3, 1, 4, 2] {
aim(&page, cx, index);
assert!(held_splashes(&page, cx).len() <= 2);
}
// Only the first splash aimed at and the last are decoded, one at a time.
for _ in 0..4 {
cx.run_until_parked();
frame_after(cx, 600);
assert!(held_splashes(&page, cx).len() <= 2);
}
assert_eq!(loads(&page, cx), before + 2);
assert_eq!(art(&page, cx).as_deref(), Some("Garen.50.30.jpg"));
assert_eq!(held_splashes(&page, cx), ["Garen.50.30.jpg"]);
}
#[gpui::test]
fn without_animations_the_illustration_changes_without_a_fade(cx: &mut TestAppContext) {
let dir = TestDir::new("ring-hover-still");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, challenge(dir.path()));
draw_loaded(cx);
let shown = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| p.banner_art.read(cx).loaded().len())
};
animations(cx, false);
aim(&page, cx, 0);
draw_loaded(cx);
assert_eq!(art(&page, cx).as_deref(), Some("Brand.50.30.jpg"));
// Only the new image: the old one has no fade to wait for.
assert_eq!(shown(&page, cx), 1);
assert_eq!(held_splashes(&page, cx), ["Brand.50.30.jpg"]);
animations(cx, true);
aim(&page, cx, 1);
draw_loaded(cx);
assert_eq!(shown(&page, cx), 2);
}
#[gpui::test]
fn the_ring_is_not_aimed_at_while_the_end_of_a_match_plays(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
statistics(0, 5, super::page_fixtures::champions(5)),
);
draw(cx);
animate(&page, cx, MatchEnd::Mark);
assert!(page.read_with(cx, |p, _| p.playback.animation.is_some()));
draw(cx);
aim(&page, cx, 3);
assert_eq!((lit(&page, cx), line(&page, cx)), (None, None));
page.update(cx, |p, cx| p.end_match(cx));
draw(cx);
aim(&page, cx, 3);
assert_eq!(lit(&page, cx), Some(4));
}
// A pointer on the ring when the end of a Match starts: the tick goes out.
#[gpui::test]
fn the_end_of_a_match_starting_ends_the_aim(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
statistics(0, 5, super::page_fixtures::champions(5)),
);
draw(cx);
aim(&page, cx, 3);
assert_eq!(lit(&page, cx), Some(4));
animate(&page, cx, MatchEnd::Mark);
assert!(page.read_with(cx, |p, _| p.playback.animation.is_some()));
assert_eq!((lit(&page, cx), line(&page, cx)), (None, None));
}
// « En partie »: the champion played is lit at rest, and it is again once the pointer leaves.
#[gpui::test]
async fn on_en_partie_leaving_the_crown_lights_the_champion_played_again(app: &mut TestAppContext) {
use super::champ_select_fixtures::finish_motion;
use super::in_game_fixtures::{in_game_ready, joueur_in_game};
let (page, mut window, mut client, _) = joueur_in_game(app, 233).await;
let cx = &mut window;
client.read(&page, cx);
finish_motion(&page, cx);
in_game_ready(&page, app).await;
let cx = &mut window;
draw(cx);
assert_eq!(lit(&page, cx), Some(233));
let other = ring_ticks(&page, cx)
.iter()
.position(|(id, _)| *id != 233)
.unwrap();
aim(&page, cx, other);
let aimed = ring_ticks(&page, cx)[other].0;
assert_eq!(lit(&page, cx), Some(aimed));
assert!(line(&page, cx).is_some());
move_to(cx, point(px(5.), px(5.)));
assert_eq!((lit(&page, cx), line(&page, cx)), (Some(233), None));
let rest = page.read_with(cx, |p, _| p.in_game.banner.splash.clone());
assert_eq!(
page.read_with(cx, |p, cx| p.banner_art.read(cx).target.clone()),
rest
);
}
@@ -0,0 +1,72 @@
//! The « Statistiques » tiles never carry the official count (#143).
use super::page_fixtures::{draw, open_page_in_season, show, statistics, switch_tab};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{Account, ProgressCheck, Status};
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
/// The page on Alice's Challenge in the current Season, with `official` as the game's count.
fn with_official(page: &Entity<Page>, cx: &mut VisualTestContext, official: ProgressCheck) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = Status {
updating: Some(Account {
puuid: "p".into(),
game_name: "Alice".into(),
tag_line: "EUW".into(),
}),
official_progress: official,
..page.status.clone()
};
page.apply(
Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end: None,
},
window,
cx,
)
})
});
}
/// The drawn height of the tile `label`, once the page is drawn again.
fn tile_height(window: &mut VisualTestContext, label: &'static str) -> f32 {
draw(window);
let bounds = window.debug_bounds(label).expect("the tile is drawn");
bounds.size.height.into()
}
#[gpui::test]
async fn the_tiles_stay_without_the_official_count(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_in_season(cx);
cx.condition(&page, |p, _| !p.busy()).await;
show(&page, &mut window, statistics(52, 100, Vec::new()));
switch_tab(&page, &mut window, Tab::Statistics);
// Without the game's count, the « Champions validés » tile has its own height, measured here;
// a note under it would make it taller. The « Tentatives » tile keeps its own height whatever
// happens to the first, so those assertions only check that it is unaffected.
let plain = tile_height(&mut window, "tile-Champions validés");
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
// The game agrees: the tiles are as tall as without the count.
with_official(&page, &mut window, ProgressCheck::Agrees(52));
assert_eq!(tile_height(&mut window, "tile-Champions validés"), plain);
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
// The game differs: the tiles are still as tall as before.
with_official(
&page,
&mut window,
ProgressCheck::Differs {
app: 50,
official: 52,
},
);
assert_eq!(tile_height(&mut window, "tile-Champions validés"), plain);
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
}
+53 -5
View File
@@ -1,4 +1,4 @@
use super::{Page, RELOAD_EVERY};
use super::{Page, RELOAD_EVERY, Tab};
use crate::worker::{Msg, spawn_refresh};
use gpui_kit::*;
@@ -12,6 +12,12 @@ impl Page {
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::GameData(catalog) => self.apply_game_data(catalog, cx),
Msg::LiveMatch(live) => self.change_live_match(live, window, cx),
Msg::RecentMatches {
generation,
matches,
} => self.apply_recent(generation, matches),
Msg::ChampSelect(champ_select) => {
if self.leave.is_some() {
if champ_select.is_none() {
@@ -24,7 +30,11 @@ impl Page {
if self.champ_select == champ_select {
return;
}
if champ_select.is_none() && self.in_champ_select() && self.may_animate(window, cx)
// The hand leaves where it is drawn; elsewhere the champ select merely ends.
if champ_select.is_none()
&& self.in_champ_select()
&& self.shown_tab == Tab::ChampSelect
&& self.may_animate(window, cx)
{
self.start_exit(window, cx);
} else {
@@ -35,11 +45,13 @@ impl Page {
status,
reload,
matches,
game_end,
} => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
if status == self.status
&& !reload
&& matches.is_empty()
&& game_end.is_none()
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed
@@ -50,9 +62,10 @@ impl Page {
self.pending_round = false;
self.progress = None;
self.crashed = false;
for event in matches {
for event in &matches {
if self.viewed().is_some_and(|a| a.puuid == event.puuid)
&& self.home_season.as_deref() == Some(event.season.as_str())
&& event.season.is_some()
&& self.home_season.as_deref() == event.season.as_deref()
{
self.hold_grid |= self.lit_by == Some(self.home_grid.entity_id());
self.queue_match(event, cx);
@@ -60,9 +73,16 @@ impl Page {
self.stats_generation += 1;
}
}
if reload {
// The Live Match's block makes it a Match: the statistics come back to the home's
// scope, which reads the Match too.
let rescoped = self.end_live_match_with_block(&matches, window, cx);
if reload && !rescoped {
self.reload_in_background(window, cx);
}
self.follow_match_end(&matches, game_end, window, cx);
if rescoped {
self.leave_gone_tab(window, cx);
}
if self.in_champ_select() {
self.prepare_champ_select(cx);
}
@@ -94,6 +114,34 @@ impl Page {
self.recompute_in_background(true, window, cx);
}
}
Msg::Matches {
generation,
matches,
} => self.apply_matches(generation, matches, window, cx),
Msg::Recap {
generation,
recap,
death,
catalog,
} => self.apply_recap(generation, *recap, *death, &catalog, cx),
Msg::DeathRecap {
match_id,
fetched,
result,
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();
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff. Show more