198 Commits
Author SHA1 Message Date
nessarandClaude Opus 5.5 a23e7ffbac Bring the window forward at the end of a game, as at a champ select
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m1s
CI / relay (push) Successful in 38s
CI / core (push) Successful in 56s
Every end of a game the page decides on (recap opened, Challenge with the
preference off, or a game left without its block) emits MatchEndShown,
formerly RecapOpened: « Paramètres » gives way and the window is raised
above the others without taking the focus, through tray::reveal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:17:36 +01:00
nessarandClaude Opus 5.5 1f0e92194a Center the player's row on the Match chosen when « Parties » opens
The Match the screen or a filter chooses now centers the displayed
Account's row, as a click in the list already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:17:36 +01:00
nessarandClaude Fable 5.2 88acc1b0df Prove a changed PUUID by champion and Placement, and fix the review findings (#150, #140)
CI / relay (pull_request) Successful in 41s
CI / core (pull_request) Successful in 58s
CI / relay (push) Successful in 42s
CI / core (push) Successful in 2m13s
A champion is unique only within a team of an Arena Match, so the proof
of a changed PUUID now requires the same champion and Placement in the
shared Match. A Friend's Riot ID resolution waits for the follower
again before each retry. The page resolves the signed-in Account once
per change instead of at each progress message, the arc's circle is
kept across counts, and the ring's paint no longer returns a value only
a test reads. Tests: a real import of twelve Matches drives the arc,
the structural test hovers a card and scrolls the grid, and Death
Recaps, blocks and Provisional Matches are read after a rekey.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 20:06:41 +01:00
nessarandClaude Fable 5.2 7b0b9863e0 Fix the verification findings of the rekey and the import arc (#150, #140)
The proof of a changed PUUID also requires the same champion in the
shared Match: anyone who played in it passed before, so a Friend whose
stale Riot ID was taken by a co-player could be merged into them. A
quota wait on a Friend's Riot ID resolution is told. The arc's paths
are built once per size and progress instead of at each paint of the
ring, and a signed-in Account the page has not read yet shows no arc.
Tests now cover the session state and the sync mark of a rekey.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:51:52 +01:00
nessarandClaude Fable 5.2 5343e49996 Show the import on the ring and the Riot quota wait (#140)
An import of 10 Matches or more of the Account shown draws a thin arc
around the ring's ticks, filled from noon as Matches arrive and gone
when the import ends. The ring stays a cached view, told at most once a
second. While the import waits for a 429's Retry-After, the progress
carries the wait and the status line counts it down each second
(« Quota Riot atteint : reprise dans 12 s »), on a timer that only
exists during the wait.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:32:12 +01:00
nessarandClaude Fable 5.2 6140bc34fb Follow an Account to its new PUUID on proof of identity (#150)
A PUUID depends on the Riot application of the API key, so the relay's
production key gives every stored Account another one. Before a request
that carries a stored PUUID (a sync, a Friend's import), the Riot ID is
resolved; when its PUUID differs and a stored published Match is among
the new PUUID's, the Account, its Matches (stored Riot responses
included), Mastery, sync mark, platform, last active mark and Friend
status move to it in one transaction. A new PUUID already stored is
merged, the published Match winning. Without proof nothing changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:21:52 +01:00
nessarandClaude Fable 5.2 073ed58bba Fix the review findings of the end-of-game key names (#154)
CI / relay (pull_request) Successful in 40s
CI / core (pull_request) Successful in 56s
CI / relay (push) Successful in 39s
CI / core (push) Successful in 1m56s
A. The fixture's game id is the synthetic one every fixture uses; the test no longer rewrites it.
B. The decoder tries the key names verified on the capture first, the other spellings after.
C. The synthetic end-of-game blocks use the real block's shape: PUUID only, no names, the real
   key spellings. The Riot-ID fallback test adds the names to its own block.
D. The captured-block follow test states that the fixture's player is the client's PUUID.
E. The recap of a Provisional Match flags the player with the Match's champion and Placement,
   not every player on that champion; a test covers a champion played by two teams.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:02:04 +01:00
nessarandClaude Opus 5.5 529b1c9370 Read the end-of-game block's real key names (#154)
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m0s
A block captured at the end of an Arena 3x6 game on Windows spells the
player's key `PUUID` and names no player, so the decoder never found the
signed-in one: every game waited for Riot's publication, and the page,
told of no Match, showed « Défi » without the end-of-game animation.

The decoder now also reads the names of that block (`PUUID`, `itemIds`,
`augmentPlatformIds`, `playerKills`, `playerDeaths`, `playerAssists`,
`damageDealtToChampions`, `damageTaken`). The capture is kept as an
anonymised fixture; a unit test decodes it and a follow test builds its
Provisional Match from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:53:09 +01:00
nessarandClaude Opus 5.5 a7387c61ce Cap Retry-After at ten minutes and fix the review's wording (#149)
CI / relay (pull_request) Successful in 45s
CI / core (pull_request) Successful in 1m20s
CI / core (push) Successful in 2m0s
CI / relay (push) Successful in 37s
The relay forwards a Retry-After of up to a day, and an import waits out
each one: the app now clamps it to between a second and ten minutes (the
relay's longest quota window) where the header is read, and says so on
SourceError::RateLimited and with_retry.

The Death Recap comments now say what happens: the relay passes any
timeline 403, a rejected key included, and the Match asked next tells
the two apart. A test plays that case (timeline refused, Match
unavailable). The shared get and SourceError no longer speak only of
the relay, the routing docs tell a region from a platform, and test
names and comments no longer speak of a key the app does not have.

The riot suites share one local server and response builder, and the
app's first-launch setup reuses open_app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:58 +01:00
nessarandClaude Opus 5.5 1eebb86902 Call Riot through the relay, without a key (#149)
Every Riot call goes to {relay}/{routing value}{Riot path} and sends no
key. The relay's address is built in (arena-tracker.nessar.fr);
relay_url in config.toml replaces it for development. A riot_api_key
left by an older version is never read, and is written back on save.

The personal keys' local pacing is gone. An import waits out each
Retry-After as often as it comes (at least a second each time), and so
do Mastery requests. A 5xx is the service unavailable, with its own
banner; a 401/403 is a refusal, which for a timeline the Match itself
confirms before it is stored, so a key failing on the relay's side
stores no refused Death Recap.

The first-launch key prompt, the key field in « Paramètres » and the
Friend refusal's « Paramètres » button are removed; the follower starts
with the app. KeyForm, KeyStore and KeyEvent become SettingsForm,
SettingsStore and SettingsEvent. README, user guide and interface spec
no longer ask for a key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:58 +01:00
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
nessarandClaude Opus 5.5 1cb7b2b11d Bring the window above the others when an Arena champ select starts (#118)
CI / core (pull_request) Successful in 1m30s
CI / core (push) Successful in 1m34s
Out of the foreground, SetWindowPos(HWND_TOP) left the restored window where
it was: under a maximized Chrome on its screen. A topmost round trip puts it
above every normal window, League included, still without activation.

A window hidden in the notification area is now shown by ShowWindow
(SW_SHOWNA): SWP_SHOWWINDOW sent GPUI no WM_SHOWWINDOW, so it never saw the
window as visible and the entry animation could not play.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:05:19 +01:00
nessarandClaude Sonnet 5.5 986c090d78 Always list the Anvil champions A to Z; sort selector moves to Autres champions (#119)
CI / core (pull_request) Successful in 1m35s
CI / core (push) Successful in 1m35s
The client lists the Anvil champions alphabetically: the row now keeps the
statistics' own order whatever sort was chosen. The selector, which only
applies to the other cards, sits beside the search of Autres champions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 13:55:00 +01:00
nessarandClaude Opus 5.5 5f309d35e7 Name the Live Match and the Friend in the glossary
CI / core (push) Successful in 1m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 11:59:05 +01:00
nessarandClaude Opus 5.5 3429e949d6 Start the 1.1.0 cycle
CI / core (push) Successful in 1m36s
1.0.0 is published: the betas of the next cycle target 1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 11:06:54 +01:00
nessarandClaude Opus 5.5 a5bd2c714e Record the 1.0.0 publication and its last trials (#62)
1.0.0 was published from 6d2605a on 2026-11-23. Without authentication,
the stable feed lists only v1.0.0 and its package verifies; trial 6 took
beta 5 to 1.0.0, and trial 14 records Windows' warning on the unsigned
installer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 11:06:44 +01:00
nessarandClaude Opus 5.5 6d2605adfa Record the final 1.0 benchmark and GPUI's floor for budget 3 (#32)
CI / core (push) Successful in 1m36s
On the reference laptop, the release build of b8e4927 holds the five
budgets. Minimised, the app skips the paint but GPUI's vsync thread still
wakes the window: by the user's decision, budget 3's CPU limit is GPUI's
floor, 1.1 % minimised and 0.35 % hidden. Budget 4 passes at the
scenario's point only: « Défi » with the grid scrolled to its end still
holds 170-174 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:58:01 +01:00
nessarandClaude Opus 5.5 a6b396ab1e Make the 1.0 frame cost budget 1 (#32)
CI / core (push) Successful in 1m33s
An empty page costs GPUI 1.41 ms at the 99th percentile on the reference
laptop, and a window move redraws the whole page without its cached
views: 2 ms could not be held without simplifying the page or changing
GPUI's behaviour. By the user's decision, the limit is the 1.0 value,
6 ms at the 99th percentile for a frame drawn, to lower after 1.0 (#106).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:31:39 +01:00
nessarandClaude Opus 5.5 b8e49276ab Hold only the table's shown portraits (#32)
CI / core (push) Successful in 1m37s
The champion table drew its 128 px portraits through GPUI's app-wide
image cache, which keeps every image it ever loaded: once « Statistiques »
had been scrolled through, all 173 stayed decoded and in the atlas, about
25 MB on the reference laptop (budget 4). The table now reads them
through its own CardImages, as the card grids do: only the rows it paints
keep theirs, and it gives them back when « Défi » or « Paramètres » is
shown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:20:30 +01:00
nessarandClaude Opus 5.5 f53db09d3e Skip GPUI's paint while the window is minimised (#32)
CI / core (push) Successful in 1m37s
GPUI's vsync thread invalidates the window at every vsync, minimised too,
and each WM_PAINT went through GPUI, which has no frame to draw then, and
DefWindowProc: the UI thread spent more minimised than visible (budget 3).
A subclass validates the paint while the window is iconic. On the manual
checks machine (240 Hz), minimised: 3.03 % of one core before, 0.22 %
after; the window draws again on restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:17:10 +01:00
nessarandClaude Opus 5.5 6311f01b49 Make GPUI's idle floor budget 2 (#32)
Idle with the window visible, every wake-up is GPUI's vsync thread and
the paint it asks for: 0.7 to 1.1 % of one core on the reference laptop,
which cannot be lowered without modifying GPUI (ADR-0004). As #32
provides, and by the user's decision, the floor becomes the limit:
1.1 %, lowered again as soon as GPUI's floor drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:17:10 +01:00
nessarandClaude Opus 5.5 245d8ac64a Record the Windows trials of 2026-11-23 (#62)
Trials 1 to 5, 7, 8 and 10 to 13 pass on the build PC, driven from WSL
by posted clicks and window captures, on the maintainer's administrator
account with real data. Trial 9 and the network cut of trial 2 were set
aside; trials 6 and 14 wait for the 1.0.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 c97b9cb4cb Say that Velopack stops the app instead of waiting for it (#62)
Velopack 1.2.161 logs « Access is denied » when it waits for the app at
each apply, although the process can be waited on with SYNCHRONIZE, and
goes straight to force-stopping what runs from the installation. The app
has quit by then, and a forced stop loses no data: config.toml is written
aside then renamed, and Matches are in SQLite transactions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 f6973b162b Record beta 5 (#62)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 2b40dcf2d3 Record the 1.0 release benchmark on the reference laptop (#32)
Measured 995f454 (1.0.0-beta.5) on the Ryzen 5 7640U, release build and
its profile build. Budgets 1, 2, 4 and the minimised CPU of budget 3 are
over; budget 5 and the no-rendering part of budget 3 hold. Idle CPU has
a floor set by GPUI's vsync thread, recorded without changing the limit.
The scenarios are written down under Measuring, with
scripts/budget-probe.ps1 to repeat them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3E5kSZykyLnuoXsBC2
2026-11-23 09:52:20 +01:00
nessarandClaude Opus 5.5 995f454a9c Run the channel trials on the installed beta first (#62)
CI / core (pull_request) Successful in 1m32s
CI / core (push) Successful in 1m37s
The build PC already went from beta 3 to beta 4 by « Redémarrer », and
runs beta 4: trials 3 to 5 use it with beta 5 published. Trials that need
a ready update then reinstall A, which updates straight to the latest beta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:55:11 +01:00
nessarandClaude Opus 5.5 9c85104161 Try the update path with betas 3, 4 and 5 (#62)
CI / core (pull_request) Successful in 1m34s
Beta 3 was already published when beta 4 was, so beta 1 would now update
straight to beta 4. A is beta 3, B beta 4 and C beta 5, published after
trial 2; B and C carry the on-demand update check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:49:22 +01:00
nessarandClaude Opus 5.5 70baa311ae Record beta 2 and document the update check button (#62)
CI / core (pull_request) Successful in 1m34s
B is 1.0.0-beta.2, published on 2026-11-22 with its four files. The user
guide now says that « Rechercher une mise à jour » runs the check on demand
and that a failed check leaves a ready update ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:46:35 +01:00
nessarandClaude Opus 5.5 fe5683bc59 Document the user guide and the 1.0 release record (#62)
Add a user guide (install, channel choice, « Mise à jour prête »,
« Redémarrer », closing to the notification area, data kept) and the 1.0
release record: versions tried, the access used for trials, the Windows
test protocol with empty results, the #32 gate and the unauthenticated
check of the public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:46:15 +01:00
nessarandClaude Sonnet 5.5 1ad36bdd5a Add a button to check for an update from the settings
CI / core (pull_request) Successful in 1m40s
CI / core (push) Successful in 1m42s
The check ran only at launch and on a channel change, so an app left
open never saw a release published since. « Rechercher une mise à jour »
runs the same check on demand, through the same gate, and the settings
now say how the last check ended: running, up to date, or why it failed.
A failed check leaves a ready update ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:40:24 +01:00
nessarandClaude Sonnet 5.5 2c9ca4552c Address review of the champ select page scroll
CI / core (pull_request) Successful in 47s
CI / core (push) Successful in 45s
- Draw the section's grid again once the draw that moved it is over: a notify
  inside a draw dirties nothing for the next one, so its rows stayed those of
  the former place.
- Keep the first row of a grid wholly below the window built, so that Tab from
  the search enters it, and scroll the page to any card the keyboard focuses.
- Leave the scrollbar its own lane in the Anvil and « Autres champions »
  sections, so it no longer covers the sort selector, and make it a view of
  its own so that its fade does not draw the whole page.
- Store the page's Paging once; correct the performance notes on scrolling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:18:35 +01:00
nessarandClaude Sonnet 5.5 15feaee8bf Scroll the whole champ select as one page
The banner, the Anvil champions and « Autres champions » now move together
on one wheel and one scrollbar. The section's grid holds no scrolling of its
own: it is as tall as all its rows and builds only those the page has in view,
read at its own render, so portraits stay in proportion to what is shown.
Its keyboard code moves to card_grid/focus.rs to keep card_grid.rs under 500
lines.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:01:55 +01:00
nessarandClaude Opus 5.5 e7ff365069 Settle names and module homes after third review (#103)
CI / core (pull_request) Successful in 1m34s
CI / core (push) Successful in 1m35s
- Rename CardPosition/CardPositions/positions() to DrawnCard/DrawnCards/
  drawn_cards(): "position" is a word CONTEXT.md avoids for Placement.
- Move the Account and status queries from page/statistics/scope.rs to
  page/displayed.rs, since the whole page uses them.
- Move the home's own statistics state (settle_home_scope, set_home_result,
  forget_home, home_is_current) to page/home/data.rs, leaving home.rs to
  queries and rendering.
- Move the profiling flag shown() from display.rs to page/profiling.rs.
- Narrow Page::new to pub(crate), and restore the domain phrase in the
  same_riot_id doc comment and the page.rs module doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:16:00 +01:00
nessar 242ecc4f28 Tighten module organization after second review (#103)
CI / core (pull_request) Successful in 1m35s
2026-11-22 18:06:44 +01:00
nessar e56da040e5 Address module split review on #103
CI / core (pull_request) Successful in 1m37s
2026-11-22 17:20:58 +01:00
nessar e43dd4510b Document Rust test layout
CI / core (pull_request) Successful in 1m31s
2026-11-22 16:58:12 +01:00
nessar c716c2c759 Group core integration tests by behavior (#102) 2026-11-22 16:49:32 +01:00
nessar 4548b6ac64 Split large core modules into focused child modules (#102) 2026-11-22 16:49:32 +01:00
nessar b9023c1d15 Split large application modules and their tests (#102) 2026-11-22 16:49:32 +01:00
nessar d0311888bb Split Page code and test suites by responsibility (#102) 2026-11-22 16:49:32 +01:00
nessar fb9c2b3cf7 Extract league client and ring test modules (#102) 2026-11-22 16:32:09 +01:00
nessar 40e8f88a98 Require focused Rust modules as files grow
CI / core (push) Successful in 1m38s
2026-11-22 16:20:40 +01:00
nessarandClaude Opus 5.5 3965b7bcc2 Let each card leave from where it is and build no card out of sight (#87)
CI / core (pull_request) Successful in 1m36s
CI / core (push) Successful in 1m36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:15:41 +01:00
nessarandClaude Opus 5.5 debf3c5232 Let the hand leave from where it is and keep the pointer's last word (#87)
Review of PR #100:
- an exit during the deal takes the moving cards down from where they are;
- an ally's confirmation lowers and greys a card lifted under the pointer too;
- the pointer moving forgets the card the keyboard waited for;
- the band of light crosses the whole window, title bar included, over the
  hand's moving cards;
- no sort, copy of a card or search of the hand per frame;
- one helper prepaints a card for both overlays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:12:24 +01:00
nessarandClaude Opus 5.5 b1c5c3a8cc Deal the hand at a champ select's entry and let it leave at its end (#87)
The entry plays once the window shows the champ select (not behind
« Paramètres »): a band of gold light sweeps the page in 900 ms, the
title comes in rising 8 px, and the Anvil champions come up from the
bottom of the window, the first at 380 ms then one every 110 ms. A card
still dealt is lifted once in its place; reasons arriving meanwhile show
on their card without dealing again, and cards arriving late with the
statistics are dealt from then.

An ally's confirmation lowers its card of the hand 8 px as it greys,
where it then rests. At the end, the hand leaves from the last card,
then the veil of the tabs covers the champ select and the end is applied
under it, the home coming back as #74 leaves it.

The moving cards are drawn by the page over the cached hand, from where
the grid placed them (`stage.rs`, as `card_lift`): the grid is never
drawn again for them, no statistics are computed, and no frame is asked
at rest. The Windows setting off, a hidden window or a covered page show
the end state at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-22 16:12:05 +01:00
nessarandClaude Opus 5.5 ee2ab5cc33 Prepare the held grid on arrival and keep the followed game apart from older Matches (#89)
CI / core (pull_request) Successful in 1m33s
CI / core (push) Successful in 1m36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:06:03 +01:00
nessarandClaude Opus 5.5 44c2d10b3b Play the strongest Match on its own champion and report every followed game (#89)
CI / core (pull_request) Successful in 1m40s
From the review of PR #99:
- Of several followed Matches waiting, the strongest plays on its own
  champion (tick, card and splash), the most recent among equals. The
  comet no longer flies to one champion's tick with another's splash.
- A game the client gave no id for, or seen before any Match gave the
  platform, is reported when the sync stores it: the client's id when
  it has one, else the newest Match newer than every one stored. A
  first import without that id stays history.
- What a Match brought comes from the Challenge's own Marks, with and
  without it, instead of a second set of rules in SQL; `fetch_and_store`
  is back to fetching and storing. `MatchEnd::Completed` takes the
  glossary's word, and its variants are documented again.
- Only the count of the banner's title rolls in, from 10 px below, as
  in the prototype; the « Dernière Partie » line still fades in.
- The Windows setting is checked where a Match is queued, and the tests
  now go through the follower round and the statistics; a test checks
  that the end state is what a reload shows.
- The Match's state is one `MatchPlayback`, ended in one place; the
  durations are named; `MarkFill`, `Changing` and `RevealFrame` replace
  bare tuples; a splash that cannot be read ends its reveal.
- `follow_client_with` takes the report itself, without a forwarding
  function. docs/performance.md describes the Match animation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:16:04 +01:00
nessar 126912fd09 Animate the Challenge after a live Match ends (#89) 2026-11-22 15:16:04 +01:00
nessarandClaude Opus 5.5 aac2f4212c Offer to launch Arena Tracker at Windows logon (#67)
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m33s
Windows alone holds the choice: the Run entry, unless the Task Manager
disabled it under StartupApproved\Run. The settings read both when they
open; switching on writes the entry and approves it again.

Started with --logon, the app opens hidden in the notification area, or
minimized when there is no tray icon, and paints no page in the first
frame, so no portrait is decoded before the window is shown. An update
ready at logon is applied silently and reopens hidden. Installing or
uninstalling removes the entry; updates keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:50:07 +01:00
nessarandClaude Opus 5.5 2770a39760 Let a whole card of the first row rise out of the list (#88)
CI / core (pull_request) Successful in 1m44s
CI / core (push) Successful in 1m37s
A lifted card was cut where its grid cuts it unless the grid showed it
whole, tested as `visible.intersect(&bounds) == bounds`. With columns of
a fractional width, the intersection rebuilds the size by subtraction
and misses the card's own by a rounding error: the first row's lifted
card was cut at the list's top edge. The test now allows a pixel of
slack on each side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-22 00:04:55 +01:00
nessarandClaude Opus 5.5 95bc4f6664 Read the lifted card from the grid and put it down more often (#88)
CI / core (pull_request) Successful in 1m38s
From the review of PR #97:
- A grid no longer shown, a card filtered out, or a wheel at either end
  of the list puts the grid's cards down at once (`PutDown`): no frame
  is asked for a card no longer drawn, and a wheel always puts it down
  while its tick stays lit under the pointer.
- The lifts hold card ids only. The grid records each placed card's
  index while it builds its rows, and the layer draws the grid's card as
  it is now: no search or copy per hover, and a lifted card shows a new
  top 1 or reason at once.
- A card the keyboard lifted goes down as soon as the pointer moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 23:29:48 +01:00
nessarandClaude Opus 5.5 162e689a40 Say that a hover no longer draws the home grid (#88)
CI / core (pull_request) Successful in 1m38s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 19:42:53 +01:00
nessarandClaude Opus 5.5 b78be1ff0b Lift the hovered card over a cached grid (#88)
The card under the pointer or the keyboard rises over its grid in about
0.35 s: 10 px with a gold glow, 4 px without for a greyed card, the
illustration zooming to 107 % inside it while the caption fades and the
sheet slides up over the lower half. Leaving it mid-way starts from where
it is; a wheel drops it at once; in the hand a veil lays on the other
cards. With Windows animations off the sheet shows without sliding and
the card stays put.

The grids never change on hover or focus any more: they record where
they placed their visible cards, and the page draws the lifted cards in
a deferred layer over them, asking for frames only while one moves.
Structural tests check that a hover, through its animation, draws no
grid, builds no card and computes no statistics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 19:18:31 +01:00
nessarandClaude Opus 5.5 c2d6296723 Cache the table, prepare a screen when shown, keep the header still (#86)
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m39s
From the review of PR #96: the champion table becomes a cached view, so
the veil's frames no longer draw it; the screen arriving is prepared
only once shown, so a switch undone under the veil prepares nothing;
turning the Windows setting off drops the animation waiting as soon as
Windows says so; the Season and Format selectors move to the title row
of « Statistiques », under the veil, so the header keeps its height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:42 +01:00
nessarandClaude Opus 5.5 d7f5e23aea End a transition when animations are turned off, read the screen drawn (#86)
From the review: the Windows setting turned off during a transition
ends it and drops the animation waiting; the errors and the official
count follow the screen drawn rather than the tab chosen; clearer names
for the veil's phases and the frames it asks for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:33 +01:00
nessarandClaude Opus 5.5 2ede37c521 Lay the animation foundation and veil the switch between tabs (#86)
Follow the Windows « Show animations » setting at start and on its
change, keep the strongest animation asked for while « Défi » is not
visible until it shows again, and switch tabs under a veil of the
page's background instead of fading or sliding the screen, which would
draw the cached views again at every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:33 +01:00
nessarandClaude Opus 5.5 0f860fda15 Keep the ring lit without a list and test the banner on the real capture (#85)
CI / core (pull_request) Successful in 1m35s
CI / core (push) Successful in 1m37s
A champ select whose Anvil list the client did not send no longer dims every
tick of the ring. k takes the singular at 0 and 1, and the line uses the same
apostrophe as the row and its fallback message. Both banners write a default
split Season as « SAISON 2 · 2026 ».

The replay test now checks the capture's own hand (k stays at 1 across the
ally's confirmation), the default and hovered illustrations, the cards'
places and the ring's Anvil list. A unit test checks which ticks stay bright.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:37:06 +01:00
nessar d74da1bee1 Show the Arena champ select in the banner (#85)
CI / core (pull_request) Successful in 1m35s
2026-11-21 18:15:19 +01:00
nessarandClaude Opus 5.5 411d139a75 Keep the ring's shapes on scroll, free a hidden splash, keep the hover's grid (#84)
CI / core (pull_request) Successful in 1m42s
CI / core (push) Successful in 1m40s
From the second review of PR #94:
- The ring's fixed shapes are made at the origin and moved where it is
  painted: a scroll that moves the ring tessellates nothing.
- The banner's splash is neither decoded nor held while the banner is
  scrolled out of view, and is given back, from the atlas too.
- The tick follows the grid that lit it: another grid saying none of its
  cards is under the pointer, or « Autres champions » folding, leaves it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 17:53:46 +01:00
nessarandClaude Opus 5.5 4fb8b37509 Lighten the ring and the splash and follow the pointer and the scope (#84)
CI / core (pull_request) Successful in 1m36s
From the review of PR #94:
- The ring tessellates its fixed shapes once per set of ticks and size;
  a hover tessellates only the lit tick.
- The banner decodes its splash itself, one at a time, on GPUI's
  low-priority queue at below-normal thread priority: a splash asked
  for while another decodes waits, so two at most are ever held.
- Opening « Paramètres » gives back the splash and the grids' portraits.
- The grid has one hover transition: a card that leaves the grid puts
  its tick out, and a wheel that moves no card keeps it.
- The home column scrolls in a low window, so the grid stays reachable.
- Entering or leaving a champ select clears the banner until the new
  scope's statistics arrive.
- Tests: drawing the ring alone draws no grid and builds no card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:50:58 +01:00
nessarandClaude Opus 5.5 d256dd61d2 Replace the home header with the banner and the ring (#84)
CI / core (pull_request) Successful in 1m32s
The banner shows the ring, a cached view with one tick per champion of
the Challenge in a fixed order, the Season, the « N / total champions
validés » title, the last Completed champion and the last Match, over
the splash of the last Completed champion, faded into the band. In a
narrow window the ring goes above the text and the splash covers the
banner. Hovering a card lights its tick.

The banner reads its splash through its own cache: two at most, the
one replaced given back from the GPU atlas too, none while
« Statistiques » is shown or without an illustration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:33:57 +01:00
nessarandClaude Opus 5.5 e28aefc3bc Expose the order of the completions and the Season's last Match (#84)
The Challenge's chronological pass that counts the Attempts now also
records the Completed champions in the order of their first top 1, and
what the Season's latest Match, all Formats, did to its champion: an
Attempt, the completing Match, or one played after completion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:33:57 +01:00
nessar cee9ff2989 Save splashes when loading art is missing and restore art notifications (#83)
CI / core (pull_request) Successful in 1m31s
CI / core (push) Successful in 1m40s
2026-11-21 14:26:59 +01:00
nessar e440d155fc Download champion splashes and cache their banner focus (#83)
CI / core (pull_request) Successful in 1m31s
2026-11-21 14:16:58 +01:00
nessar 3de8fd527c Document focus contrast and set row highlight opacity explicitly (#82)
CI / core (pull_request) Successful in 1m37s
CI / core (push) Successful in 1m32s
2026-11-21 13:56:57 +01:00
nessar eb21db17ad Strengthen theme contrast and cover the heading font fallback (#82)
CI / core (pull_request) Successful in 1m31s
2026-11-21 12:36:56 +01:00
nessar bfb29e02fe Apply the logo palette and Unbounded headings across the app (#82)
CI / core (pull_request) Successful in 1m33s
2026-11-21 12:14:04 +01:00
nessarandClaude Sonnet 5.5 48729f83ad Document the green-CI requirement to merge into develop and main
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 11:42:05 +01:00
nessarandClaude Sonnet 5.5 d42125724e Document the L'Anneau identity and version its reference page (#81)
CI / core (pull_request) Successful in 1m37s
CI / core (push) Successful in 1m31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 11:33:12 +01:00
nessarandClaude Opus 5.5 8784c6eb6c Say how a champion absent from Riot's mastery list counts (#76)
CI / core (pull_request) Successful in 1m42s
CI / core (push) Successful in 1m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:28 +01:00
nessarandClaude Opus 5.5 72f7a239c0 Tell why the home has no cards yet and tidy the cards code after review (#72)
Without statistics the home said « Aucun champion trouvé » under a count of
0; it now shows the same notice as the champ select (loading, no Account),
from a small StatsNotice enum instead of compared strings.

Also from the review: a structural test that hovering or scrolling
« Autres champions » recomputes no statistics, as docs/performance.md says;
English comments; one card aspect (core's CARD_ASPECT) and one cards_dir;
one builder for the champ select cards, one count badge, one test temp dir;
clearer names (with_cards_behaviour, home_has_own_scope).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 213d693ab8 Record the fourth greying reason and what the redesign established (#74)
The spec gains « Indisponible », agreed for a champion the client does not
offer, and records what #74 and #76 established about the Anvil champions
list and the Mastery Points, with what is left to the Windows check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 4612d89a3d Keep a whole row in "Autres champions" and tidy the cards code (#75)
- "Autres champions" grid is never shorter than one card row.
- A Format change keeps the home's statistics (#71); the home cards
  are built when "Defi" is shown again; hidden grids give back their
  decoded portraits; the card holds its portrait as Arc<Path>.
- Unavailability becomes Unpickable (glossary), "selection" becomes
  "champ select" in comments (#74); the statistics error is shown by
  the banner only during a champ select.
- Column breakpoints follow the mockup's max-width rules, the home
  tools row is search, filters, sort; stale comments fixed.
- Tests: whole row, hidden grids, stats scopes, error shown once, and
  the capture's reasons end to end in the open section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 2cd8b2c545 Document the third cached grid and the portraits given back (#77)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 18b06f8ea6 Read the portraits folders once and stop the card pass offline (#77)
The statistics list the portraits folder and its cards subfolder once
instead of checking about 340 files. The tall-portrait pass is skipped
when the catalog refresh failed and stops at the first network error;
the core tells after each attempt whether a portrait was saved, so the
worker's throttle can tell the page after any attempt, not only saves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 485d7b9065 Show a missing-statistics notice once during a champ select (#75)
With the statistics missing, the Anvil area no longer repeats « Aucune Saison
en cours » when the header already says it, and « Autres champions » is not
offered since there is nothing to browse.

Test tidy-ups: the saved-portraits assertion message says what is checked,
main.rs tests use card_images' TestDir instead of their own TempDir, and the
test-only accessors of Page move after the last method so choose_sort reads
with its doc comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 28d86d48b7 Drop the champ select helpers the text view used (#74)
ChampSelect::remaining and current_row only served the text champ select
view that #74 removed. The follow test now looks the current pick up in the
statistics rows and builds the pickable, not Completed set from can_pick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 a457a19fe5 Sort the cards by Mastery Points or A to Z and remember the choice (#76)
The statistics rows carry the Mastery Points: None for an Account whose
points were never fetched, Some(0) for a champion missing from the last
list. One card order, computed only when the statistics or the preference
change, feeds the home grid, the Anvil row and « Autres champions ». The
sort selector stays visible during a champ select, the choice is saved
with the other preferences, and the sheet shows the Mastery Points
(unknown ones after the known, and not as zero).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 815daf33cb Show the tall portraits on the cards, decoded only while shown (#77)
The champions thread downloads the card portraits after the square ones
and tells the page at most once a second while they arrive, plus once at
the end, so each shows without a restart. A card shows its tall portrait,
the square icon while it is missing, else its plain background.

Each card grid reads its portraits through its own image cache: only the
cards it paints are loaded, and what its previous render did not paint is
dropped at its next render, from the GPU atlas too, and all of it with the
grid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:43:02 +01:00
nessarandClaude Opus 5.5 f1e8808082 Add the folding « Autres champions » section to the Arena champ select (#75)
Folded at each new selection, it lists the champions without an anvil (all of
them, as « Tous les champions », when the client gave no Anvil list) with the
anvil row's cards, order and greyed reasons. Its own search filters only this
section. Its cards are built only while it is open, in a cached virtualized
grid. The `others` profiling part is documented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:39:43 +01:00
nessarandClaude Opus 5.5 6f2a6244cc Show the Anvil champions as cards during an Arena champ select (#74)
The home takes the selection: the Challenge of the signed-in Account for the
current Season, then a row of the Anvil champions in the home grid's order with
the reasons Validé, Banni, Pris par un allié and Indisponible. The old text view
is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:32:51 +01:00
nessarandClaude Opus 5.5 05b8cc6d60 Hide the hovered sheet when the grid scrolls (#73)
A wheel scroll moves cards under a still pointer without a hover event, so
the sheet could stay on a card no longer under it. The grid now forgets the
hovered card on scroll; the next mouse move hovers the right one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:32:01 +01:00
nessarandClaude Opus 5.5 796fae11b7 Show the champion's sheet on hover and keyboard focus (#73)
The sheet covers the card with the Season's Matches, Wins, best Placement
and Attempts, and the date of the first top 1 for a Completed champion. Its
lines are prepared in Card::from_row; only the shown cards build it. The
grid keeps the hovered card and one focus handle per card id, and handles
Tab and Shift-Tab itself, scrolling the next card's row into view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:30:50 +01:00
nessarandClaude Opus 5.5 bd9f1c7c98 Show the home's champions as a grid of cards with Played and Win marks (#72)
Add the champion card (portrait, name, "Joué" and "Victoire" marks, greyed with
"Validé" once completed) and a cached, virtualised card grid that replaces the
home's table. Columns follow the window width as in the mockup. Cards are built
once per statistics change; hovering or scrolling only redraws the grid.
Profiling part `home-list` becomes `cards`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:21:16 +01:00
nessarandClaude Opus 5.5 bd4de1ec05 Tell why a champ select makes a champion unavailable (#74)
Split the excluded set into banned and taken_by_ally, add
ChampSelect::unavailability (banned, taken_by_ally, not_offered; never for
the player's own pick) and make the anvil list an Option so an unreadable
list is not read as an empty one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 9c13e14072 Document the profiling parts and the hover probe for the two tabs (#71)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 43a6b05f56 Split the home Challenge from the Statistics tab (#71)
The app opens on « Défi »: the Season of the Challenge, a one-line
counter with a thin progress line, and the champion table filtered by
Tous / Restants / Validés and a search of its own. A navigation of two
keyboard-focusable buttons leads to « Statistiques », which keeps the
analysis, with the charts now ordered curve, Placements, Attempts.

The home follows the Season chosen on Statistiques (the current one for
all Seasons) and ignores the Format. Its statistics come from the same
worker job as the Statistics tab's, and are only computed apart when the
two scopes differ. The home renders no chart and the hidden tab's table
is not rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 6c1a62cf6a Move the statistics rendering into page/statistics.rs (#71)
Move only, no behaviour change: the tiles, the charts row and the table
section leave the page, which keeps the shared state, the header row, the
banners and the champ select view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 0350f66cfd Rename the statistics page module to page (#71)
Rename only, no behaviour change: the page is about to hold two tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 5ce8c777c4 Fetch Mastery Points from the Riot API and add the champion sort preference (#76)
The tracker asks Riot for each Account's champion mastery (platform host) right
after a successful sync, and after a Match fetched by id is added, so no new
polling. Lists are stored per Account in one transaction and read back with
Tracker::mastery (None = never fetched). A failed fetch keeps the last values
and records no problem. Preferences gain champion_sort (mastery or name).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:09:18 +01:00
nessarandClaude Opus 5.5 50c0427958 Keep tall card portraits cropped to the card size (#77)
Add ChampionSource::card_portrait (Data Dragon loading art) and
Tracker::refresh_card_portraits, which downloads the missing ones, crops them
to the card's 0.68 aspect at the mockup's 24 % focus, shrinks them to
308 x 453 px and saves them as JPEG in portraits/cards via a .part file.
ChampionRow gains card_portrait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:08:57 +01:00
nessarandClaude Opus 5.5 34e8fb8a50 Expose the Season Challenge figures of each champion card (#72)
Add ChampionChallenge (Matches, Wins, best Placement, date of the first
top 1) and Marks (Played, Won, Completed) on ChampionRow::challenge. They
cover one Account and one Season across all Formats, so the Format filter
never changes them. Computed in the existing chronological pass.

The first top 1 date (#73) comes from the first top 1 by start time, with
the same day convention as the progress curve, so a later or out-of-order
import never changes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:07:52 +01:00
nessarandClaude Opus 5.5 209059cf10 Define the major release that needs the full benchmark as X.0.0 (#61)
CI / core (pull_request) Successful in 37s
CI / core (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:53:18 +01:00
nessarandClaude Opus 5.5 400ac154f9 Ignore the files Gitea lists when it creates a draft (#61)
CI / core (pull_request) Successful in 1m18s
On a private test repository, a stable whose tag only existed locally
stopped before publishing: Gitea 28.1 lists unrelated files in its reply
to the draft creation when it does not have the tag yet, and the command
tried to remove them (HTTP 404, nothing published). A new draft has no
files, so only a draft found by its tag is emptied. Record the stable
run: refusals, an older main commit, a local-only tag, reruns, the next
beta and the channel queries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:44:45 +01:00
nessarandClaude Opus 5.5 5f4332a79f Publish a stable of main from the build PC (#61)
CI / core (pull_request) Successful in 1m18s
scripts/publish-beta becomes scripts/publish with a channel argument.
`scripts/publish stable [commit]` publishes the Cargo.toml version of a
commit on main whose CI checks passed: it builds with scripts/package,
checks the signed files against the tag and commit before creating
anything, tags vX.Y.Z on that commit, then publishes a complete draft as
a normal Release. A stable tag never moves; reruns reuse, complete or
refuse as for betas. Releases now name their target commit, so a tag
that only exists locally is never created on the default branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:27:53 +01:00
nessarandClaude Opus 5.5 19c4cf940d Publish betas from the build PC instead of a CI runner (#60)
CI / core (pull_request) Successful in 1m19s
CI / core (push) Successful in 35s
A runner on the build PC would run pull request code without isolation
next to the signing key, and only that PC has the Windows toolchain.
scripts/publish-beta now runs there: it fetches develop and the beta
tags, refuses a commit absent from develop on Gitea or whose CI checks
did not pass, and keeps the numbering, draft-then-publish and reruns.
The key stays in its file; the beta job and its secret are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:52:32 +01:00
nessarandClaude Opus 5.5 5e757d2a63 Record the beta publication run and the runner 6 setup (#60)
CI / core (pull_request) Successful in 1m14s
CI / beta (pull_request) Skipped
A private test repository went through a main push, develop creation, a
two-commit push, two close pushes, a failing check, reruns of a complete
and of an interrupted publication, and a job cancelled mid-build; the five
betas verify with their own executables, and a pull request token is
refused write access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:14:26 +01:00
nessarandClaude Opus 5.5 9b87492b43 Publish a numbered beta after each validated push to develop (#60)
The beta job runs after the core checks on a host-mode WSL runner with the
Windows toolchain, builds the push's commit with scripts/package and
publishes it as a prerelease: tag, draft, the four files, then publish.
The cycle target is the workspace version (1.0.0); beta tags are the
counter, created atomically after the build. A rerun reuses or completes
its own publication; a single runner serializes the jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:29:50 +01:00
nessarandClaude Opus 5.5 093078731e Test that a release newer than a failed one is applied at launch (#59)
CI / core (pull_request) Successful in 36s
CI / core (push) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:11:15 +01:00
nessarandClaude Opus 5.5 ab3c6964a5 Apply the update through « Redémarrer » or at the next launch (#59)
The settings show « Redémarrer » next to « Mise à jour prête ». It
verifies the kept package of the chosen channel again, hands exactly
that file to Velopack with `Update.exe apply --waitPid <pid> --package
<file>`, then quits as « Quitter » does (WM_QUIT, never hidden in the
notification area). Velopack 1.2.161 reads the file in place, waits for
the app to exit, replaces current\ and opens the new version once, or
the old one again after a failure.

After « Quitter », the next launch does the same before loading the
app, offline too, but only in the single instance: a shortcut launched
while the app runs still just brings its window back (#50).

An attempt record, <channel>-<version>.attempt next to the package
folder, holds the installer's process id. A launch that finds it never
retries on its own: it waits for a running installer (a close second
launch, or the old version reopened after a failure), then either
leaves the app to the new version or opens the current one with a
one-time notice. « Redémarrer » retries; a newer release starts fresh.
The record survives a new download of the same version, since Velopack
deletes a package it cannot open.

Velopack's swap has no rollback between its two renames; this residual
risk is recorded in ADR-0005 and docs/paquets-windows.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:02:57 +01:00
nessarandClaude Opus 5.5 8e12abf7f4 Choose the update channel and download authenticated updates (#58)
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 1m16s
The settings offer Stable or Bêta. The choice is saved only once made;
until then the installed version's channel applies, so the beta
installer follows Bêta. Updates never change a saved choice.

Each launch, and each channel change, runs one check on a below-normal
thread. It lists the channel's Releases through the public Gitea API
(betas are pre-releases) and takes the highest version above the
installed one. The package is downloaded into
%LOCALAPPDATA%\arena-tracker\updates\partial, verified with
verify_release, then kept as <channel>-<version>; another channel's
package is removed before any network access. Only then does a green
title-bar button show « Mise à jour prête » and open the settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:25 +01:00
nessarandClaude Opus 5.5 24aca3c93d Reopen the window without focus when an Arena champ select starts (#63)
CI / core (pull_request) Successful in 45s
CI / core (push) Successful in 46s
A minimized window, or one hidden in the notification area, comes back above
the other windows while League keeps the keyboard. An already visible window is
left alone, and the window stays open after the champ select.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:57:53 +01:00
nessarandClaude Opus 5.5 c5ed246668 Record the Windows packaging decisions and today's install run (#57)
CI / core (pull_request) Successful in 1m18s
CI / core (push) Successful in 1m20s
ADR-0005: Velopack packer only, our own Ed25519 manifest, full packages,
accepted root-launcher path (same-user write), static C runtime.
The guide records the 1.0.0 run: non-elevated silent install, Start Menu
shortcut opening the installed exe with existing data, uninstall and
reinstall keeping config, Seasons and Parties, tampered package refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:53:48 +01:00
nessarandClaude Opus 5.5 611a19ce28 Link the C runtime statically instead of shipping vcruntime140.dll (#57)
The installed app then depends only on Windows libraries, whatever Visual
Studio redistributable the build machine has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:47:54 +01:00
nessarandClaude Opus 5.5 18e9db54fc Verify the whole release folder in core and rebuild packaged sources (#57)
Address the code review of the carried-over work:
- scripts/package extracts the snapshot with fresh mtimes, so the shared
  target never reuses a workspace crate built from other sources.
- core::verify_release owns the release-folder contract (file names, size
  limits, signature, identity, digest) and returns Error::InvalidUpdate; it is
  tested natively with real folders, oversized manifests and missing files.
- The app's --verify-release only adds the build identity and commit check.
- French script messages, clearer path helpers, accurate Velopack stub facts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:43:02 +01:00
nessarandClaude Opus 5.5 f90ae109b9 Package a per-user Windows installer and signed full update packages (#57)
Work in progress carried over from the main checkout: scripts/package builds
one version from one commit, packs it with vpk 1.2.161 (full packages only),
signs a manifest with Ed25519 and checks the result with the built executable.
The core verifies the signed manifest and package digest before any unpacking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:34:14 +01:00
nessarandClaude Opus 5.5 6d07a9641f Address single-instance review findings (#50)
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 39s
- Reopen the window even when the relaunch's ack event is gone.
- Exit quietly instead of panicking on timeout or Win32 error; bound the startup gate wait.
- Fail softly in accept_relaunches; name the locks (Primary, HeldMutex).
- Share window_hwnd, derive REOPEN from TRAY_MESSAGE, name the marker.
- Test a crashed primary and a relaunch that finds no window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:09:47 +01:00
nessar a11bc277f2 Restore the existing window on relaunch (#50)
Elect one process per Windows session before starting GPUI or opening the database. Let the existing window handle reopen requests and preserve its current state.
2026-11-19 23:09:47 +01:00
nessar fac082e51f Documenter la refonte d’Arena Tracker et sa maquette interactive
CI / core (pull_request) Successful in 38s
CI / core (push) Successful in 1m19s
2026-11-19 23:08:13 +01:00
nessar 304d958c72 Fix the final champ select review findings (#13)
CI / core (pull_request) Successful in 51s
CI / core (push) Successful in 49s
2026-11-19 22:17:14 +01:00
nessarandClaude Opus 5.5 cf15eeeb8f Decode client events from their data and keep the draft on a timeout (#13)
Event frames are [8, topic, {data, eventType, uri}]; decode_event returned the
whole envelope, so the cached session had no localPlayerCellId and the
pickable/disabled/anvil lists ignored the update until a fresh GET. It now
returns the envelope's data (null on Delete, which the cache already ignores).
The tests use enveloped frames, including one from raw text to the cached state.

transport_error mapped every non-TLS error to Absent, so one request timing out
while the client loads the draft sent the page back to statistics. A timeout or
an I/O error other than connection refused is now Other, which champ_select_with
treats as transient. Other readers of ClientError only use .ok(), so nothing
else changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:17:14 +01:00
nessar 5ba3251875 Fix champ select review findings (#13)
- redraw the page on hover and lock-in changes, and reset the settings form
  when champ select takes the window away
- keep the current pick when a client read fails; only a real answer that
  the draft is over ends it
- read the client once per wake and share it between the follower and the
  live selection, reuse session event payloads, and touch only the cached
  champion list an event concerns
- replay the captured raw client responses in the fake and cover the list
  cache, event updates and the anvil-champion read
- name the five champions anvil champions and the set pickable, document
  them, and prepare redraw strings ahead of render
2026-11-19 22:17:14 +01:00
nessar f4a9e5e7a8 Show live Arena champion picks and crowd favorites (#13) 2026-11-19 22:17:14 +01:00
nessar fabaa8a60f Record the five anvil champions from the same Arena session 2026-11-19 22:17:14 +01:00
nessar 9d9b67666b Capture Arena 3x6 bans, hovers and lock-in for #13 2026-11-19 22:17:14 +01:00
nessarandClaude Opus 5.5 650dfd4bfa Address Inter font review findings (#52)
CI / core (pull_request) Successful in 38s
CI / core (push) Successful in 1m14s
- Set Inter only when DirectWrite resolves its family, so a name
  mismatch keeps the system font instead of a fallback on every run.
- Rename init to init_theme and share the family name as a constant.
- Make the test prove a semibold face: its glyphs are wider.
- Ship the license from the same Inter release as the font.
- Shorten the search placeholder so it fits at the minimum width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:10:16 +01:00
nessar 1016b68e41 Use Inter as the interface font
CI / core (pull_request) Successful in 40s
2026-11-19 21:56:16 +01:00
nessar a537999229 research
CI / core (push) Successful in 50s
2026-11-19 20:09:16 +01:00
nessarandClaude Opus 5.5 ad3f491f45 Refine the title bar and add a one-time tray notice (#24)
CI / core (pull_request) Successful in 1m8s
CI / core (push) Successful in 1m17s
- Drop the out-of-scope responsive stats page and scrolling settings
  form; keep the minimum window size.
- A refresh keeps the following mode: a followed Account stays followed,
  a pinned one stays pinned.
- Flat 32 px title bar with full-height buttons, so Fermer is reachable
  in the screen corner when maximized; Windows close colours on hover.
- Read the maximized state directly instead of caching it; split the
  crash arms; share the window-button styling.
- Keep close to tray on by default.
- Notify once, the first time closing hides the app in the notification
  area; recorded as tray_notice_shown in config.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:24:16 +01:00
nessar 797b7e83e0 Address title-bar review findings (#24)
CI / core (pull_request) Successful in 1m9s
2026-11-18 23:24:23 +01:00
nessar 23eb933a68 Add a custom Windows title bar (#24)
CI / core (pull_request) Successful in 1m17s
2026-11-18 21:11:21 +01:00
nessar a2d58c000c Préciser les dégâts observables par objet et amélioration (#23)
CI / core (pull_request) Successful in 42s
CI / core (push) Successful in 40s
2026-11-18 00:45:52 +01:00
nessar 21212a11a2 Document Arena match statistics and post-game availability (#23) 2026-11-18 00:45:52 +01:00
nessar d7bd69c35d Add tray and theme settings (#21)
CI / core (pull_request) Successful in 1m13s
CI / core (push) Successful in 44s
2026-11-18 00:36:15 +01:00
338 changed files with 58738 additions and 5663 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# Link the MSVC C runtime into the executable: the installer ships no vcruntime140.dll (ADR-0005).
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+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/
+30 -1
View File
@@ -1,4 +1,6 @@
# 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
on:
@@ -6,6 +8,11 @@ on:
push:
branches:
- main
- develop
# CI never publishes: a read-only job token is enough.
permissions:
contents: read
jobs:
core:
@@ -26,3 +33,25 @@ jobs:
- name: Tests
run: cargo test -p arena-tracker-core --locked
- 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
+2
View File
@@ -1,3 +1,5 @@
/target
*.local.toml
.env
__pycache__/
.scratch/
+18
View File
@@ -7,6 +7,24 @@ The app must stay as fluid and light as possible: it never feels slow and never
- Do not modify GPUI or gpui-component to meet a budget: reduce the app's own rendering cost (ADR-0004).
- A part of the page gets its own view for a reason: it owns state that changes on its own (the champion table: sort, selection, scroll, hover), or it is a cached view with a structural test (`docs/performance.md`), its gain checked at the next release benchmark. Other parts render as functions in their parent's render.
## Rule #2: focused modules
When adding behavior or tests would grow a Rust file and leave it above 500 lines, counting inline tests, extract a cohesive responsibility or test suite into a focused module in the same change. Use Rust modules and render functions for these splits and follow Rule #1 for GPUI view boundaries.
### Rust test layout
- Keep small unit-test suites next to the implementation in an inline `#[cfg(test)] mod tests { ... }`. The child module can access private items in its parent.
- Move larger unit-test suites to a child file such as `src/ring/tests.rs`, declared with `#[cfg(test)] mod tests;`. Split suites by behavior as they grow.
- 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
+59
View File
@@ -8,6 +8,30 @@ Personal tracking of League of Legends Arena matches, centred on progress throug
A finished Arena game played by an Account with one champion, in one Format.
_Avoid_: Game, session
**Live Match**:
An Arena game the active Account is playing, from its start until it ends and becomes a Match.
_Avoid_: Current game, ongoing match, game in progress
**Match Recap**:
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
@@ -28,6 +52,13 @@ _Avoid_: Victory
The goal of getting a top 1 with every champion in the game in as few Attempts as possible, scoped to one Account and one Season across all Formats, mirroring how the game client counts it.
_Avoid_: Checklist, goal, Arena God
**Mark**:
One of three milestones for a champion within a Challenge, earned for the first Match, the first Win, and the first top 1 respectively. A first Match ending in a top 1 earns all three Marks at once.
_Avoid_: Point, Fame
**Mastery Points**:
The champion mastery score that League of Legends gives an Account for a particular champion.
**Completed**:
The state of a champion that has at least one top 1 within a given Challenge.
_Avoid_: Done, validated, won
@@ -48,6 +79,22 @@ _Avoid_: Split, run
A League of Legends account; the active Account is the one signed in to the game client.
_Avoid_: Player, profile, summoner
**Friend**:
An Account added by its Riot ID to view its Challenge; it stays a Friend even if it later signs in to the game client.
_Avoid_: Watched account, guest, buddy
**Champ select**:
The draft before an Arena Match, where each player bans and picks a champion; only an Arena champ select opens the champ select view.
_Avoid_: Draft, selection
**Anvil champions**:
The five champions the game favours in the current Arena patch and shows during champ select; the game client calls them crowd favorites.
_Avoid_: Crowd favorites, favorites
**Pickable**:
A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player.
_Avoid_: Available, owned
**Official Progress**:
The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge.
_Avoid_: Riot challenge, tracker
@@ -59,12 +106,24 @@ The interface is in French. Each glossary term has one French word in user-facin
| Term | In the interface |
| --- | --- |
| 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 |
| Attempt | Tentative |
| First Try | du premier coup |
| Completed | validé |
| Win | Victoire |
| Season | Saison |
| Account | Compte |
| Friend | Ami |
| Champ select | Sélection des champions |
| Anvil champions | Champions de l'Enclume |
| Pickable | Disponible |
| Official Progress | Progression officielle |
| Placement, Format, Top N | unchanged |
Generated
+50 -2
View File
@@ -219,19 +219,28 @@ dependencies = [
[[package]]
name = "arena-tracker"
version = "0.1.0"
version = "1.1.0"
dependencies = [
"arena-tracker-core",
"base64 0.23.1",
"embed-resource",
"gpui-kit",
"gpui-pre",
"image",
"log",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
]
[[package]]
name = "arena-tracker-core"
version = "0.1.0"
version = "1.1.0"
dependencies = [
"base64 0.23.1",
"image",
"log",
"ring",
"rusqlite",
"rustls",
"serde",
@@ -242,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"
@@ -286,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"
@@ -919,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"
@@ -3163,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"
@@ -6903,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"
+4 -3
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 = "0.1.0"
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/>.
+18 -5
View File
@@ -1,9 +1,11 @@
# Arena Tracker
Application de bureau Windows qui suit les Parties d'Arena de League of Legends. Le vocabulaire du domaine est dans `CONTEXT.md` et les décisions d'architecture dans `docs/adr/`.
Application de bureau Windows qui suit les Parties d'Arena de League of Legends. Pour l'installer et l'utiliser : [guide d'utilisation](docs/guide-utilisation.md). Le vocabulaire du domaine est dans `CONTEXT.md` et les décisions d'architecture dans `docs/adr/`.
Règle n°1 : l'application reste fluide et légère, sans jamais donner l'impression de ralentir ni l'application ni l'ordinateur. Ses budgets mesurables (temps par image, CPU au repos, mémoire, travail de fond) et la façon de les mesurer sont dans `docs/performance.md`.
L’installateur par utilisateur et la commande de construction des paquets Stable et Bêta sont décrits dans le [guide des paquets Windows](docs/paquets-windows.md). Les branches main et develop, la cible du cycle et la publication des bêtas et des stables sont décrites dans [Publication](docs/publication.md).
## Prérequis
- Windows avec la chaîne d'outils Rust (rustup), version 1.98 ou plus récente, accessible depuis WSL sous le nom `cargo.exe`.
@@ -32,17 +34,19 @@ magick -background none -density 384 logo.svg -resize 1024x1024 -define icon:aut
## Configuration
L'application lit `%APPDATA%\arena-tracker\config.toml`, en dehors du dépôt. Le fichier est facultatif : au premier lancement, l'application demande la clé API Riot (à demander sur le portail développeur Riot), l'enregistre dans ce fichier et la prend en compte sans redémarrage. La clé se change ensuite dans `Paramètres`. Exemple de fichier, avec des valeurs fictives :
L'application lit `%APPDATA%\arena-tracker\config.toml`, en dehors du dépôt. Le fichier est facultatif, et aucune clé API Riot n'est à saisir : les appels à Riot passent par le service d'Arena Tracker, qui garde la clé (ADR-0008, [service intermédiaire](docs/service-relais.md)). Exemple de fichier, avec des valeurs fictives :
```toml
riot_api_key = "RGAPI-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # clé du portail développeur Riot
riot_id = "NomDeJeu#TAG" # facultatif
region = "europe" # facultatif, "europe" par défaut
relay_url = "http://127.0.0.1:8080" # facultatif, pour le développement : un autre service que https://arena-tracker.nessar.fr
```
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement.
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement. Le `riot_api_key` d'une version antérieure est ignoré et laissé dans le fichier.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée.
L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique, `champion_sort` : `mastery` ou `name`, absent tant que le joueur n'a pas choisi, le tri se faisant alors par points de maîtrise) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant.
## Tests
@@ -57,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.
+19
View File
@@ -3,18 +3,37 @@ name = "arena-tracker"
edition.workspace = true
rust-version.workspace = true
version.workspace = true
license.workspace = true
[features]
profile = ["gpui-kit/profiler"]
[dependencies]
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"] }
[target.'cfg(windows)'.dependencies]
raw-window-handle = "0.6"
windows = { version = "0.62", features = [
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_Threading",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
# The GPUI that gpui-kit pins (upgrade them together), for its test context. Not gpui-kit's own
# test-support: its gpui-fast features would force older wgpu and others into Cargo.lock.
gpui = { package = "gpui-pre", version = "=0.3.12", features = ["test-support"] }
# Splits the Arena champ select capture into its frames (the same version as the core's).
serde_json = "1.0.154"
[build-dependencies]
embed-resource = "3.0.12"
+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2022 The Unbounded Project Authors (https://github.com/googlefonts/unbounded)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+22
View File
@@ -1,2 +1,24 @@
// GPUI loads icon resource 1 for the window and its taskbar entry; File Explorer shows it too.
1 ICON "icon.ico"
#ifdef ARENA_RELEASE
#include "release-version.h"
1 VERSIONINFO
FILEVERSION ARENA_VERSION_NUMBERS
PRODUCTVERSION ARENA_VERSION_NUMBERS
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "ProductName", "Arena Tracker"
VALUE "FileVersion", ARENA_VERSION_TEXT
VALUE "ProductVersion", ARENA_VERSION_TEXT
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0409, 1200
END
END
#endif
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="48 48 160 160" width="48" height="48">
<path fill="currentColor" d="M68 186 L52 86 L98 126 L128 66 L158 126 L204 86 L188 186 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 188 B

+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)
);
}
}
+323
View File
@@ -0,0 +1,323 @@
//! The banner's illustration: the splash of one champion, decoded off the UI thread at low
//! priority and held by the banner alone, never by GPUI's app-wide asset cache (rule #1: memory in
//! proportion to what is shown, background work at low priority).
//!
//! It holds two splashes at most: the one shown and the one replacing it, which shows once
//! decoded. The one it replaces is then given back, in memory and in the windows' atlas, as the
//! card portraits are (#77). A decode cannot be stopped once started, so only one runs at a time:
//! a splash asked for meanwhile waits for its end.
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use arena_tracker_core::{Splash, SplashFocus};
use gpui_kit::*;
use crate::motion::MATCH_SETTLE;
use crate::worker::BelowNormal;
const FADE: Duration = Duration::from_millis(500);
/// The splash of a champion just Completed settles in (#89): it waits for its image, then comes
/// in enlarged and shrinks back.
enum Reveal {
AwaitingImage,
Settling(Instant),
}
/// The incoming splash's frame during a reveal.
#[derive(Clone, Copy)]
pub(crate) struct RevealFrame {
/// 1 at rest, above while it settles.
pub zoom: f32,
pub opacity: f32,
}
impl RevealFrame {
const REST: RevealFrame = RevealFrame {
zoom: 1.,
opacity: 1.,
};
}
pub struct BannerArt {
pub(crate) target: Option<Rc<Splash>>,
reveal: Option<Reveal>,
previous: Option<(Rc<Splash>, Arc<RenderImage>, Instant)>,
/// The splash shown, and its image; none when it could not be read.
shown: Option<(Rc<Splash>, Option<Arc<RenderImage>>)>,
/// The decode running, of which splash.
decoding: Option<(Rc<Splash>, Task<()>)>,
/// The splash the banner shows next: decoded when the running decode ends, if it is not
/// that one. None while the banner shows no illustration.
wanted: Option<Rc<Splash>>,
/// Decodes started.
#[cfg(test)]
pub(crate) loads: usize,
}
impl BannerArt {
pub fn new(cx: &mut App) -> Entity<BannerArt> {
let art = cx.new(|_| BannerArt {
target: None,
reveal: None,
previous: None,
shown: None,
decoding: None,
wanted: None,
#[cfg(test)]
loads: 0,
});
// The page is gone: so is the splash, from every window's atlas too.
cx.observe_release(&art, |art, cx| {
art.drop_previous(None, cx);
art.drop_shown(None, cx);
})
.detach();
art
}
/// A splash is settling in.
#[cfg(test)]
pub(crate) fn revealing(&self) -> bool {
self.reveal.is_some()
}
/// Shows `target` as the splash of a champion just Completed: it settles in.
pub(crate) fn reveal(&mut self, target: Option<Rc<Splash>>, cx: &mut Context<Self>) {
self.set_target(target, cx);
self.reveal = self.target.as_ref().map(|_| Reveal::AwaitingImage);
cx.notify();
}
/// The incoming splash's frame now, asking for the next while it settles. It starts at its
/// first decoded frame, even on a slow disk; one that cannot be read has nothing to settle.
pub(crate) fn reveal_frame(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> RevealFrame {
if cx.reduce_motion() {
self.reveal = None;
}
let Some(reveal) = &mut self.reveal else {
return RevealFrame::REST;
};
let now = cx.background_executor().now();
let start = match *reveal {
Reveal::Settling(start) => start,
Reveal::AwaitingImage => match &self.shown {
Some((shown, image)) if Some(shown) == self.target.as_ref() => {
if image.is_none() {
self.reveal = None;
return RevealFrame::REST;
}
*reveal = Reveal::Settling(now);
now
}
_ => return RevealFrame::REST,
},
};
let elapsed = now.duration_since(start).as_secs_f32();
let t = elapsed / MATCH_SETTLE;
if t >= 1. {
self.reveal = None;
return RevealFrame::REST;
}
window.request_animation_frame();
RevealFrame {
zoom: 1. + 0.1 * (1. - t).powi(2),
opacity: if self.previous.is_some() {
1.
} else {
(elapsed / FADE.as_secs_f32()).min(1.)
},
}
}
pub fn set_target(&mut self, target: Option<Rc<Splash>>, cx: &mut Context<Self>) {
if self.target != target {
self.reveal = None;
self.target = target;
self.wanted = None;
cx.notify();
}
}
/// The outgoing image is painted over the new one with decreasing opacity.
pub(crate) fn previous_opacity(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<f32> {
let (_, _, start) = self.previous.as_ref()?;
let elapsed = cx.background_executor().now().duration_since(*start);
if elapsed >= FADE || cx.reduce_motion() {
self.drop_previous(Some(window), cx);
return None;
}
window.request_animation_frame();
Some(1. - elapsed.as_secs_f32() / FADE.as_secs_f32())
}
pub(crate) fn previous_image(&self) -> Option<(Arc<RenderImage>, SplashFocus)> {
self.previous
.as_ref()
.map(|(splash, image, _)| (image.clone(), splash.focus))
}
fn drop_previous(&mut self, window: Option<&mut Window>, cx: &mut App) {
if let Some((_, image, _)) = self.previous.take() {
cx.drop_image(image, window);
}
}
/// For the paint of `splash`: the image to paint and its focus. That is `splash` once
/// decoded, and until then the splash shown before it. The art notifies when it changes. A
/// splash that cannot be read shows nothing.
pub fn image(
&mut self,
splash: &Rc<Splash>,
cx: &mut Context<Self>,
) -> Option<(Arc<RenderImage>, SplashFocus)> {
if self.wanted.as_ref() != Some(splash) {
self.wanted = Some(splash.clone());
}
let shown_wanted = self
.shown
.as_ref()
.is_some_and(|(shown, _)| shown == splash);
if !shown_wanted && self.decoding.is_none() && self.previous.is_none() {
self.decode(splash.clone(), cx);
}
let (shown, image) = self.shown.as_ref()?;
Some((image.clone()?, shown.focus))
}
fn decode(&mut self, splash: Rc<Splash>, cx: &mut Context<Self>) {
#[cfg(test)]
{
self.loads += 1;
}
let path = splash.path.clone();
let task = cx.spawn(async move |art, cx| {
let image = cx
.background_executor()
.spawn_with_priority(Priority::Low, async move { decode(&path) })
.await;
let _ = art.update(cx, |art, cx| art.decoded(image, cx));
});
self.decoding = Some((splash, task));
}
/// The running decode ended: its splash replaces the one shown if the banner still wants
/// it, else it is dropped (it was never painted) and the wanted one decodes.
fn decoded(&mut self, image: Option<Arc<RenderImage>>, cx: &mut Context<Self>) {
let Some((splash, _)) = self.decoding.take() else {
return;
};
if self.wanted.as_ref() == Some(&splash) {
if image.is_some()
&& !cx.reduce_motion()
&& animations_enabled()
&& let Some((old, Some(previous))) = self.shown.take()
{
self.previous = Some((old, previous, cx.background_executor().now()));
} else {
self.drop_shown(None, cx);
}
self.shown = Some((splash, image));
cx.notify();
} else if let Some(wanted) = self.wanted.clone()
&& self
.shown
.as_ref()
.is_none_or(|(shown, _)| *shown != wanted)
{
drop(image);
self.decode(wanted, cx);
}
}
/// Gives back the splash shown, from `window`'s atlas and every other window's.
fn drop_shown(&mut self, window: Option<&mut Window>, cx: &mut App) {
if let Some((_, Some(image))) = self.shown.take() {
cx.drop_image(image, window);
}
}
/// Drops the splash, in memory and in the window's atlas, for a banner that is not shown or
/// has no illustration. A decode running ends unused.
pub fn release(&mut self, window: &mut Window, cx: &mut App) {
self.reveal = None;
self.wanted = None;
self.drop_previous(Some(window), cx);
self.drop_shown(Some(window), cx);
}
/// The splashes held: shown, or decoding.
#[cfg(test)]
pub(crate) fn held(&self) -> Vec<std::path::PathBuf> {
let shown = self.shown.as_ref().map(|(splash, _)| splash);
let decoding = self.decoding.as_ref().map(|(splash, _)| splash);
[
self.previous.as_ref().map(|(splash, _, _)| splash),
shown,
decoding,
]
.into_iter()
.flatten()
.map(|splash| splash.path.clone())
.collect()
}
/// The splash decoded and shown.
#[cfg(test)]
pub(crate) fn loaded(&self) -> Vec<Arc<RenderImage>> {
self.shown
.iter()
.filter_map(|(_, image)| image.clone())
.chain(self.previous.iter().map(|(_, image, _)| image.clone()))
.collect()
}
}
/// Reads and decodes a stored splash (a JPEG) into what the GPU takes, BGRA, at below-normal
/// priority. None when it cannot be read.
fn decode(path: &Path) -> Option<Arc<RenderImage>> {
let _below = BelowNormal::enter();
let bytes = std::fs::read(path).ok()?;
let mut pixels = image::load_from_memory_with_format(&bytes, image::ImageFormat::Jpeg)
.ok()?
.into_rgba8();
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
Some(Arc::new(RenderImage::new(vec![image::Frame::new(pixels)])))
}
#[cfg(all(windows, not(test)))]
fn animations_enabled() -> bool {
use windows::Win32::UI::WindowsAndMessaging::{
SPI_GETCLIENTAREAANIMATION, SystemParametersInfoW,
};
let mut enabled = windows::core::BOOL::default();
// SPI_GETCLIENTAREAANIMATION writes one BOOL to the supplied pointer.
unsafe {
SystemParametersInfoW(
SPI_GETCLIENTAREAANIMATION,
0,
Some((&raw mut enabled).cast()),
Default::default(),
)
.is_ok()
&& enabled.as_bool()
}
}
#[cfg(any(not(windows), test))]
fn animations_enabled() -> bool {
true
}
+420
View File
@@ -0,0 +1,420 @@
//! The champion card: the one representation of a champion, on the home and in the Arena champ
//! select. A `Card` is built once when the statistics change; `card` only lays it out.
mod detail;
use detail::{caption, reasons, shade, sheet};
use std::path::Path;
use std::sync::{Arc, LazyLock};
use arena_tracker_core::{ChampionRow, Marks, Unpickable};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::text::{ordinal, thousands};
use crate::theme::{LOGO_GOLD, ON_GOLD, gold_glow, surface};
/// Width over height: the ratio the stored portraits are cropped to.
pub const ASPECT: f32 = arena_tracker_core::CARD_ASPECT as f32;
const RADIUS: f32 = 10.;
/// The border is inside the radius: the layers it holds are rounded one pixel less.
const INNER_RADIUS: f32 = RADIUS - 1.;
// The caption and badges sit on the dark shade, in both themes: their colours are fixed.
const MARK_ON: u32 = 0xffffff;
const MARK_OFF: u32 = 0xd3d4db;
const MARK_OFF_RING: u32 = 0xbfc1cd;
const BADGE_BG: u32 = 0x11152aee;
const BADGE_TEXT: u32 = 0xffa0a0;
// The sheet is dark in both themes, like the shade it replaces.
const SHEET_BG: u32 = 0x0d1021f5;
const SHEET_LABEL: u32 = 0xc5cbe0;
// The sheet's lines, in order.
const PLAYED: &str = "Parties";
const WINS: &str = "Victoires";
const BEST_PLACEMENT: &str = "Meilleur Placement";
const ATTEMPTS: &str = "Tentatives";
const MASTERY: &str = "Points de maîtrise";
const UNKNOWN: &str = "Inconnus";
/// Only on a Completed champion.
pub const FIRST_TOP_1: &str = "Premier top 1";
const NONE: &str = "—";
/// Why a card is greyed out, in the order the badges are shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
/// At least one top 1 in the Season.
Completed,
/// Banned in the champ select.
Banned,
/// Confirmed by an ally in the champ select.
TakenByAlly,
/// The champ select does not offer the champion.
NotOffered,
}
impl Reason {
pub fn label(self) -> &'static str {
match self {
Reason::Completed => "Validé",
Reason::Banned => "Banni",
Reason::TakenByAlly => "Pris par un allié",
Reason::NotOffered => "Indisponible",
}
}
fn badge(self, id: u32) -> Div {
let badge = div()
.h_flex()
.items_center()
.gap(px(4.))
.px(px(6.))
.py(px(3.))
.rounded(px(4.))
.text_size(px(10.))
.font_weight(FontWeight::SEMIBOLD)
.debug_selector(move || format!("reason-{id}-{}", self.label()));
let ordinary = |badge: Div, icon: IconName| {
badge
.bg(rgba(BADGE_BG))
.text_color(rgb(BADGE_TEXT))
.child(Icon::new(icon).size(px(12.)))
};
let badge = match self {
Reason::Completed => {
static CROWN: LazyLock<Arc<Image>> = LazyLock::new(|| {
let svg = include_str!("../assets/crown.svg")
.replace("currentColor", &format!("#{ON_GOLD:06x}"));
Arc::new(Image::from_bytes(ImageFormat::Svg, svg.into_bytes()))
});
badge
.bg(rgb(LOGO_GOLD))
.text_color(rgb(ON_GOLD))
.child(img(CROWN.clone()).size(px(12.)))
}
Reason::Banned => ordinary(badge, IconName::Ban),
Reason::TakenByAlly => ordinary(badge, IconName::User),
Reason::NotOffered => ordinary(badge, IconName::EyeOff),
};
badge.child(self.label())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Card {
pub id: u32,
pub name: SharedString,
/// The tall portrait, else the square icon while the tall one is not downloaded yet.
/// Shared, so drawing the card clones a pointer rather than a path.
pub portrait: Option<Arc<Path>>,
pub marks: Marks,
/// In display order. A card with any reason is greyed.
pub reasons: Vec<Reason>,
/// The lines of the sheet shown on hover and focus, as label and value, prepared with the
/// card so showing it reads nothing.
pub sheet: Vec<(&'static str, SharedString)>,
}
/// How far a card is lifted over its grid (#88), drawn over it while the pointer or the keyboard
/// is on it: it rises, its illustration zooms in, its caption fades and its sheet slides up from
/// the bottom.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pose {
/// The Marks the end of a followed Match has just given, filling in gold (#89).
pub mark_fill: Option<MarkFill>,
/// 0 at rest, 1 lifted all the way.
pub progress: f32,
/// The hand's veil on this card: 0 to 1.
pub veil: f32,
/// Off with the Windows « Show animations » setting: the sheet shows, the card stays put.
pub moves: bool,
}
/// A card's Marks before the end of a followed Match, and how far the gold of those it gained has
/// filled in: 0 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MarkFill {
pub before: Marks,
pub progress: f32,
}
impl MarkFill {
/// The opacity of a Mark's gold: filling in when just gained, full when it was already on.
fn opacity(fill: Option<MarkFill>, was_on: fn(&Marks) -> bool) -> f32 {
fill.filter(|f| !was_on(&f.before))
.map_or(1., |f| f.progress)
}
}
/// How high a card rises: less for a greyed one, which cannot be picked.
const RISE: f32 = 10.;
const GREYED_RISE: f32 = 4.;
/// How much the illustration zooms in, inside the card.
const ZOOM: f32 = 0.07;
/// How far the sheet slides up, and the caption down.
const SHEET_SLIDE: f32 = 14.;
const CAPTION_SLIDE: f32 = 6.;
const CAPTION_BOTTOM: f32 = 12.;
/// The hand's veil on the other cards, as the mockup's `rgba(9, 11, 24, .42)`.
const VEIL: u32 = 0x090b18;
const VEIL_OPACITY: f32 = 0.42;
impl Pose {
/// How many pixels the card is above its place.
pub fn rise(&self, card: &Card) -> f32 {
if !self.moves {
return 0.;
}
self.progress * if card.greyed() { GREYED_RISE } else { RISE }
}
fn zoom(&self) -> f32 {
if self.moves { self.progress * ZOOM } else { 0. }
}
}
/// The hand's veil on a card at rest in it, `veil` from 0 to 1.
pub fn veil_color(veil: f32) -> Hsla {
Hsla::from(rgb(VEIL)).opacity(VEIL_OPACITY * veil)
}
/// The radius of a card, for what is drawn over one.
pub const CARD_RADIUS: f32 = RADIUS;
impl Card {
/// A row without a Challenge (no Season) has no Marks.
pub fn from_row(row: &ChampionRow) -> Card {
let marks = row.challenge.map_or(
Marks {
played: false,
won: false,
completed: false,
},
|challenge| challenge.marks(),
);
Card {
id: row.champion.id,
name: row.champion.name.clone().into(),
portrait: row
.card_portrait
.as_deref()
.or(row.portrait.as_deref())
.map(Arc::from),
marks,
reasons: if marks.completed {
vec![Reason::Completed]
} else {
Vec::new()
},
sheet: sheet_lines(row),
}
}
/// Adds the champ select's reasons after the Season's. The player's own pick has none.
pub fn with_unpickable(mut self, unpickable: Unpickable) -> Card {
let Unpickable {
banned,
taken_by_ally,
not_offered,
} = unpickable;
for (applies, reason) in [
(banned, Reason::Banned),
(taken_by_ally, Reason::TakenByAlly),
(not_offered, Reason::NotOffered),
] {
if applies {
self.reasons.push(reason);
}
}
self
}
pub fn greyed(&self) -> bool {
!self.reasons.is_empty()
}
}
/// 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. « 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())
};
let mut lines = vec![
(PLAYED, count(challenge.map(|c| c.matches))),
(WINS, count(challenge.map(|c| c.wins))),
(
BEST_PLACEMENT,
challenge
.and_then(|c| c.best_placement)
.map_or_else(|| NONE.into(), |placement| ordinal(placement).into()),
),
(ATTEMPTS, count(row.attempts)),
// Unknown is not zero: the points were never fetched for this Account.
(
MASTERY,
row.mastery_points
.map_or_else(|| UNKNOWN.into(), |points| thousands(points).into()),
),
];
if let Some(date) = challenge.and_then(|c| c.completed_on) {
lines.push((FIRST_TOP_1, date.to_string().into()));
}
lines
}
/// One card at rest, as wide as its parent gives it, `ASPECT` wide over tall. Nothing about it
/// changes on hover or focus, so a grid of them stays cached: the card under the pointer or the
/// keyboard is drawn again over it, lifted (`lifted`). A focus handle makes it a tab stop. The
/// caller adds its own listeners.
pub fn card(card: &Card, focus: Option<&FocusHandle>, cx: &App) -> Stateful<Div> {
let id = card.id;
let root = div().flex_1().min_w_0().aspect_ratio(ASPECT);
face(root, card, None, cx)
.id(("card", id))
.when_some(focus, |el, handle| el.track_focus(handle))
.debug_selector(|| format!("card-{id}"))
}
/// The card drawn over its grid in `pose`, `size` as its place there; the caller sets it
/// `pose.rise` above. It has no listener: the pointer still meets the card at rest under it.
pub fn lifted(card: &Card, pose: Pose, size: Size<Pixels>, cx: &App) -> Div {
let theme = cx.theme();
let progress = pose.progress;
let shadows = if !pose.moves || progress == 0. {
Vec::new()
} else if card.greyed() {
vec![drop_shadow(12., 24., -14., 0.6 * progress)]
} else {
vec![
drop_shadow(18., 34., -14., 0.65 * progress),
BoxShadow {
color: gold_glow(theme).opacity(progress),
offset: point(px(0.), px(0.)),
blur_radius: px(28.),
spread_radius: px(-8.),
inset: false,
},
]
};
let id = card.id;
face(div().w(size.width).h(size.height), card, Some(pose), cx)
.shadow(shadows)
.debug_selector(move || format!("lifted-{id}"))
}
/// The card at rest drawn over its grid, `size` as its place there, under the hand's `veil`
/// (0 to 1): the champ select's motion (#87) moves it while the grid stays put. It has no
/// listener.
pub fn moving(card: &Card, veil: f32, size: Size<Pixels>, cx: &App) -> Div {
let id = card.id;
let pose = (veil > 0.).then_some(Pose {
mark_fill: None,
progress: 0.,
veil,
moves: true,
});
face(div().w(size.width).h(size.height), card, pose, cx)
.debug_selector(move || format!("moving-{id}"))
}
fn drop_shadow(y: f32, blur: f32, spread: f32, opacity: f32) -> BoxShadow {
BoxShadow {
color: hsla(0., 0., 0., opacity),
offset: point(px(0.), px(y)),
blur_radius: px(blur),
spread_radius: px(spread),
inset: false,
}
}
/// What a card shows, at rest (`None`) or lifted, in `root`.
fn face(root: Div, card: &Card, pose: Option<Pose>, cx: &App) -> Div {
let theme = cx.theme();
let greyed = card.greyed();
let id = card.id;
let progress = pose.map_or(0., |pose| pose.progress);
let zoom = pose.map_or(0., |pose| pose.zoom());
// Towards the accent as the card rises, as the hover and focus border did.
let border = theme.border.blend(theme.ring.opacity(progress));
root.relative()
.overflow_hidden()
.rounded(px(RADIUS))
.border_1()
.border_color(border)
.bg(surface(theme))
.children(card.portrait.as_ref().map(|path| {
// Zoomed in, the illustration overflows the card on every side, and is cut square:
// `corners` rounds it again.
img(path.clone())
.absolute()
.left(relative(-zoom / 2.))
.top(relative(-zoom / 2.))
.w(relative(1. + zoom))
.h(relative(1. + zoom))
.rounded(px(INNER_RADIUS))
.object_fit(ObjectFit::Cover)
.grayscale(greyed)
}))
// Stands for the mockup's `brightness(.72)`, which the image element cannot do.
.when(greyed, |el| {
el.child(
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(hsla(0., 0., 0., 0.28)),
)
})
.child(shade())
.when(greyed, |el| el.child(reasons(id, &card.reasons)))
.when(progress < 1., |el| {
let slide = if pose.is_some_and(|pose| pose.moves) {
CAPTION_SLIDE * progress
} else {
0.
};
el.child(
caption(card, pose.and_then(|p| p.mark_fill))
.bottom(px(CAPTION_BOTTOM - slide))
.opacity(1. - progress),
)
})
.when(progress > 0., |el| {
let slide = if pose.is_some_and(|pose| pose.moves) {
SHEET_SLIDE * (1. - progress)
} else {
0.
};
el.child(sheet(card).bottom(px(-slide)).opacity(progress))
})
.when(zoom > 0., |el| el.child(corners(theme.background)))
.children(pose.filter(|pose| pose.veil > 0.).map(|pose| {
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(veil_color(pose.veil))
}))
}
/// What lies outside the card's rounded corners, in `background`: a frame whose inner edge is
/// the card's radius, of which only the corners fall inside the card.
fn corners(background: Hsla) -> Div {
let width = RADIUS;
div()
.absolute()
.top(px(-width))
.left(px(-width))
.right(px(-width))
.bottom(px(-width))
.rounded(px(RADIUS + width))
.border(px(width))
.border_color(background)
}
#[cfg(test)]
mod tests;
+148
View File
@@ -0,0 +1,148 @@
use gpui_kit::component::{Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{
CAPTION_BOTTOM, Card, INNER_RADIUS, MARK_OFF, MARK_OFF_RING, MARK_ON, MarkFill, Reason,
SHEET_BG, SHEET_LABEL,
};
use crate::theme::{LOGO_GOLD, ON_GOLD};
/// Over the lower half of the card, as the mockup's `.sheet`: the name, then a line per figure,
/// on a shade that darkens from its top. Only a lifted card builds it.
pub(super) fn sheet(card: &Card) -> Div {
let id = card.id;
let clear = rgba(SHEET_BG & 0xffffff00);
div()
.absolute()
.left_0()
.right_0()
.rounded_b(px(INNER_RADIUS))
.v_flex()
.justify_end()
.pt(px(44.))
.px(px(12.))
.pb(px(12.))
.bg(linear_gradient(
180.,
linear_color_stop(clear, 0.),
linear_color_stop(rgba(SHEET_BG), 0.34),
))
.text_size(px(12.))
.text_color(rgb(SHEET_LABEL))
.debug_selector(|| format!("sheet-{id}"))
.child(
div()
.mb(px(6.))
.text_size(px(17.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(card.name.clone()),
)
.children(card.sheet.iter().map(|(label, value)| {
div()
.h_flex()
.justify_between()
.gap(px(4.))
.py(px(1.5))
.debug_selector(|| format!("sheet-{id}-{label}"))
.child(*label)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(value.clone()),
)
}))
}
/// Keeps the caption readable on any portrait.
pub(super) fn shade() -> Div {
let clear = rgba(0x090b1800);
let dark = rgba(0x090b18f2);
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(linear_gradient(
180.,
linear_color_stop(clear, 0.5),
linear_color_stop(dark, 0.92),
))
}
pub(super) fn reasons(id: u32, reasons: &[Reason]) -> Div {
div()
.absolute()
.top(px(9.))
.left(px(8.))
.right(px(8.))
.h_flex()
.items_start()
.flex_wrap()
.gap(px(3.))
.children(reasons.iter().map(|reason| reason.badge(id)))
}
pub(super) fn caption(card: &Card, fill: Option<MarkFill>) -> Div {
div()
.absolute()
.left(px(12.))
.right(px(8.))
.bottom(px(CAPTION_BOTTOM))
.v_flex()
.child(
div()
.text_size(px(18.))
.font_weight(FontWeight::SEMIBOLD)
.line_height(relative(1.18))
.text_color(white())
.child(card.name.clone()),
)
.child(
div()
.h_flex()
.items_center()
.flex_wrap()
.mt(px(7.))
.gap_x(px(10.))
.gap_y(px(4.))
.child(mark(
"Joué",
card.marks.played,
MarkFill::opacity(fill, |m| m.played),
))
.child(mark(
"Victoire",
card.marks.won,
MarkFill::opacity(fill, |m| m.won),
)),
)
}
/// A dot, filled with a check when on, its gold at `fill` opacity, and its label.
fn mark(label: &'static str, on: bool, fill: f32) -> Div {
div()
.h_flex()
.items_center()
.gap(px(4.))
.text_size(px(10.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(rgb(if on { MARK_ON } else { MARK_OFF }))
.child(
div()
.flex()
.items_center()
.justify_center()
.size(px(11.))
.rounded_full()
.border_1()
.border_color(rgb(if on { LOGO_GOLD } else { MARK_OFF_RING }))
.when(on, |dot| {
dot.bg(Hsla::from(rgb(LOGO_GOLD)).opacity(fill))
.text_color(rgb(ON_GOLD))
.child(Icon::new(IconName::Check).size(px(8.)))
}),
)
.child(label)
}
+283
View File
@@ -0,0 +1,283 @@
use std::path::PathBuf;
use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, Date, Unpickable};
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::{Card, FIRST_TOP_1, Reason};
fn row(challenge: Option<ChampionChallenge>) -> ChampionRow {
ChampionRow {
champion: Champion {
id: 4,
key: "TwistedFate".into(),
name: "Twisted Fate".into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
challenge,
mastery_points: Some(154_320),
}
}
fn day() -> Date {
Date {
year: 2026,
month: 3,
day: 2,
}
}
fn marks(card: &Card) -> (bool, bool) {
(card.marks.played, card.marks.won)
}
#[test]
fn a_champion_never_played_has_no_mark_and_keeps_its_colours() {
let card = Card::from_row(&row(Some(ChampionChallenge::default())));
assert_eq!(marks(&card), (false, false));
assert!(card.reasons.is_empty());
assert!(!card.greyed());
}
#[test]
fn a_champion_played_without_a_win_has_only_the_played_mark() {
let challenge = ChampionChallenge {
matches: 3,
best_placement: Some(4),
..Default::default()
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, false));
assert!(!card.greyed());
}
#[test]
fn a_champion_with_a_win_but_no_top_1_is_in_colour_with_both_marks() {
let challenge = ChampionChallenge {
matches: 2,
wins: 1,
best_placement: Some(2),
completed_on: None,
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, true));
assert!(!card.marks.completed);
assert!(!card.greyed());
}
#[test]
fn a_completed_champion_is_greyed_with_the_validated_reason() {
let challenge = ChampionChallenge {
matches: 4,
wins: 2,
best_placement: Some(1),
completed_on: Some(day()),
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, true));
assert_eq!(card.reasons, [Reason::Completed]);
assert_eq!(card.reasons[0].label(), "Validé");
assert!(card.greyed());
assert_eq!(card.name.as_ref(), "Twisted Fate");
}
fn lines(card: &Card) -> Vec<(&'static str, String)> {
card.sheet
.iter()
.map(|(label, value)| (*label, value.to_string()))
.collect()
}
#[test]
fn the_sheet_of_a_champion_never_played_is_empty_figures_without_a_date() {
let mut row = row(Some(ChampionChallenge::default()));
row.attempts = Some(0);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "0".to_string()),
("Victoires", "0".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "0".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_of_a_remaining_champion_has_its_best_placement_and_no_date() {
let challenge = ChampionChallenge {
matches: 5,
wins: 2,
best_placement: Some(2),
completed_on: None,
};
let mut row = row(Some(challenge));
row.attempts = Some(5);
let card = Card::from_row(&row);
assert_eq!(
lines(&card),
[
("Parties", "5".to_string()),
("Victoires", "2".into()),
("Meilleur Placement", "2ᵉ".into()),
("Tentatives", "5".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
assert!(card.sheet.iter().all(|(label, _)| *label != FIRST_TOP_1));
}
#[test]
fn the_sheet_of_a_completed_champion_has_the_date_of_its_first_top_1() {
let challenge = ChampionChallenge {
matches: 6,
wins: 3,
best_placement: Some(1),
completed_on: Some(day()),
};
let mut row = row(Some(challenge));
row.attempts = Some(4);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "6".to_string()),
("Victoires", "3".into()),
("Meilleur Placement", "1ᵉʳ".into()),
("Tentatives", "4".into()),
("Points de maîtrise", "154\u{202f}320".into()),
("Premier top 1", "02/03/2026".into()),
]
);
}
#[test]
fn the_sheet_of_a_row_without_a_season_has_dashes_and_no_date() {
let card = Card::from_row(&row(None));
assert_eq!(
lines(&card),
[
("Parties", "—".to_string()),
("Victoires", "—".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "—".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_shows_zero_points_as_zero_and_unknown_points_as_unknown() {
let mut row = row(None);
row.mastery_points = Some(0);
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "0".to_string())
);
row.mastery_points = None;
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "Inconnus".to_string())
);
}
#[test]
fn a_row_without_a_challenge_has_no_marks() {
let card = Card::from_row(&row(None));
assert_eq!(marks(&card), (false, false));
assert!(!card.greyed());
}
#[test]
fn the_tall_portrait_is_shown_and_the_square_icon_stands_in_while_it_is_missing() {
let tall = PathBuf::from("portraits/cards/TwistedFate.jpg");
let square = PathBuf::from("portraits/TwistedFate.png");
let both = ChampionRow {
portrait: Some(square.clone()),
card_portrait: Some(tall.clone()),
..row(None)
};
assert_eq!(
Card::from_row(&both).portrait.as_deref(),
Some(tall.as_path())
);
let downloading = ChampionRow {
card_portrait: None,
..both
};
assert_eq!(
Card::from_row(&downloading).portrait.as_deref(),
Some(square.as_path())
);
// Neither: the card keeps its plain background.
assert_eq!(Card::from_row(&row(None)).portrait, None);
}
fn completed_row() -> ChampionRow {
row(Some(ChampionChallenge {
matches: 1,
wins: 1,
best_placement: Some(1),
completed_on: Some(day()),
}))
}
fn reasons_of(banned: bool, taken_by_ally: bool, not_offered: bool) -> Unpickable {
Unpickable {
banned,
taken_by_ally,
not_offered,
}
}
#[test]
fn the_champ_selects_reasons_add_up_in_a_fixed_order() {
let all = reasons_of(true, true, true);
let card = Card::from_row(&completed_row()).with_unpickable(all);
assert_eq!(
card.reasons,
[
Reason::Completed,
Reason::Banned,
Reason::TakenByAlly,
Reason::NotOffered
]
);
let labels: Vec<_> = card.reasons.iter().map(|r| r.label()).collect();
assert_eq!(
labels,
["Validé", "Banni", "Pris par un allié", "Indisponible"]
);
let card = Card::from_row(&row(None)).with_unpickable(reasons_of(false, true, false));
assert_eq!(card.reasons, [Reason::TakenByAlly]);
let card = Card::from_row(&completed_row()).with_unpickable(reasons_of(true, false, false));
assert_eq!(card.reasons, [Reason::Completed, Reason::Banned]);
}
#[test]
fn a_champion_the_champ_select_does_not_hold_back_is_not_greyed_by_it() {
let card = Card::from_row(&row(None)).with_unpickable(Unpickable::default());
assert!(card.reasons.is_empty());
assert!(!card.greyed());
// The player's own pick has no reason from the champ select, but a Completed one stays.
let card = Card::from_row(&completed_row()).with_unpickable(Unpickable::default());
assert_eq!(card.reasons, [Reason::Completed]);
assert!(card.greyed());
let card = Card::from_row(&row(None)).with_unpickable(reasons_of(false, false, true));
assert!(card.greyed());
}
+458
View File
@@ -0,0 +1,458 @@
//! The card grid: all the cards a list shows, in rows of the same count, only the visible rows
//! built (a grid that scrolls by itself, or one the page scrolls). It is its own view because it
//! owns the hover of its cards, the scrolling of its list when it has one, and the portraits they
//! show (`card_images`). Its cards never change on hover or focus: the card under the pointer or
//! the keyboard is drawn lifted over the grid (`card_lift`), from where the grid last placed it.
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card::{Card, Reason, card};
use crate::card_images::{self, CardImages};
mod focus;
pub use focus::init;
use focus::{CONTEXT, CardFocus, NextCard, PreviousCard};
mod geometry;
use geometry::{MAX_COLUMNS, Metrics, rows_in_view};
pub use geometry::{MAX_WIDTH, TAKEN_DROP};
mod layout;
pub use layout::{CardHovered, DrawnCard, DrawnCards, Paging, PutDown, RevealRow};
pub struct CardGrid {
/// All the cards in the order the page gives (the chosen sort); replaced when the statistics
/// or the sort change.
cards: Rc<[Card]>,
/// Indices into `cards`, after the filter and the search.
shown: Vec<usize>,
scroll: UniformListScrollHandle,
/// The card under the pointer or the keyboard, which is lifted.
hovered: Option<u32>,
/// Where the visible cards were drawn last.
drawn_cards: DrawnCards,
/// How far the list was scrolled when last drawn: a wheel that leaves it there (at either
/// end) moves no card from under the pointer.
drawn_scroll: Pixels,
/// One per card id, kept across `set_cards` and dropped with the card.
focus: HashMap<u32, CardFocus>,
/// The cards changed since the focus handles were last matched to them.
focus_stale: bool,
/// All the rows built as a plain column, with no scrolling of its own: for a short list
/// whose height comes from its content (the Anvil champions row of a champ select).
fit_content: bool,
/// For a grid the page scrolls: where that scrolling has it, which says the rows built. The
/// grid is as tall as all its rows, and holds no scrolling of its own.
paged: Option<Paging>,
/// The portraits of the cards it paints, its own: made by its first render.
images: Option<Entity<CardImages>>,
/// Guard the light rendering in tests.
#[cfg(test)]
pub(crate) renders: usize,
#[cfg(test)]
pub(crate) card_builds: usize,
#[cfg(test)]
pub(crate) set_cards_calls: usize,
}
impl EventEmitter<CardHovered> for CardGrid {}
impl EventEmitter<PutDown> for CardGrid {}
impl EventEmitter<RevealRow> for CardGrid {}
impl CardGrid {
pub fn new() -> CardGrid {
CardGrid {
cards: Rc::new([]),
shown: Vec::new(),
scroll: UniformListScrollHandle::new(),
hovered: None,
drawn_cards: DrawnCards::default(),
drawn_scroll: Pixels::ZERO,
focus: HashMap::new(),
focus_stale: false,
fit_content: false,
paged: None,
images: None,
#[cfg(test)]
renders: 0,
#[cfg(test)]
card_builds: 0,
#[cfg(test)]
set_cards_calls: 0,
}
}
/// A grid that is as tall as its rows and builds them all. It has the home grid's cards and
/// metrics. The parent uses the same row height to lay out the cached hand.
pub fn fit_content() -> CardGrid {
CardGrid {
fit_content: true,
..CardGrid::new()
}
}
/// A grid as tall as all its rows, whose scrolling is the page's: it builds the rows that
/// scrolling has in view of the window.
pub fn paged(paging: Paging) -> CardGrid {
CardGrid {
paged: Some(paging),
..CardGrid::new()
}
}
/// How tall the grid is with all its rows, none for an empty one: what a grid that is
/// as tall as its rows (the hand, a paged grid) is given.
pub fn rows_height(&self, window_width: Pixels) -> Option<Pixels> {
let metrics = Metrics::of(window_width);
let rows = self.shown.len().div_ceil(metrics.columns);
(rows > 0).then(|| px(metrics.row_height() * rows as f32))
}
/// Replaces the cards; the grid is drawn again only when they differ (reloads keep coming
/// during an import). `set_shown` follows, as the indices belong to the cards.
pub fn set_cards(&mut self, cards: Rc<[Card]>, cx: &mut Context<Self>) {
#[cfg(test)]
{
self.set_cards_calls += 1;
}
if *self.cards != *cards {
self.cards = cards;
self.focus_stale = true;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
fn set_hovered(&mut self, id: u32, hovered: bool, cx: &mut Context<Self>) {
let next = match (hovered, self.hovered) {
(true, _) => Some(id),
(false, Some(current)) if current == id => None,
(false, current) => current,
};
self.hover(next, cx);
}
/// The one change of the card under the pointer or the keyboard: it is told (the ring
/// lights that card's tick, the card is lifted over the grid), and the grid is not drawn
/// again.
fn hover(&mut self, next: Option<u32>, cx: &mut Context<Self>) {
self.hover_by(next, false, cx);
}
fn hover_by(&mut self, next: Option<u32>, by_keyboard: bool, cx: &mut Context<Self>) {
if next != self.hovered {
self.hovered = next;
cx.emit(CardHovered {
id: next,
by_keyboard,
});
}
}
/// The pointer moved while the keyboard had lifted a card, or the pointer went to another
/// grid: none of its cards is under the pointer or the keyboard any more.
pub fn put_down(&mut self, cx: &mut Context<Self>) {
self.hover(None, cx);
}
/// The card under the pointer is no longer shown (filtered out, or gone with new cards):
/// none is hovered until the pointer moves again.
fn forget_hover_if_gone(&mut self, cx: &mut Context<Self>) {
let shown = |id| {
(self.shown.iter()).any(|&ix| self.cards.get(ix).is_some_and(|card| card.id == id))
};
if self.hovered.is_some_and(|id| !shown(id)) {
self.hover(None, cx);
// It would settle back where it is no longer drawn.
cx.emit(PutDown);
}
}
/// How far down the list is scrolled, as its next layout will put it: a wheel past either end
/// is held there.
fn scrolled_to(&self) -> Pixels {
let handle = &self.scroll.0.borrow().base_handle;
handle
.offset()
.y
.max(-handle.max_offset().y)
.min(Pixels::ZERO)
}
/// The grid is not shown any more: its portraits are given back, in memory and in the
/// window's atlas, and load again when it is drawn.
pub fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// Nor is any of its cards under the pointer: the ring's tick goes out.
self.hover(None, cx);
cx.emit(PutDown);
self.drawn_cards.borrow_mut().clear();
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();
}
}
/// The indices of the cards shown, in order.
pub fn shown(&self) -> &[usize] {
&self.shown
}
pub fn set_shown(&mut self, shown: Vec<usize>, cx: &mut Context<Self>) {
if self.shown != shown {
self.shown = shown;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<SharedString> {
self.shown
.iter()
.filter_map(|&ix| self.cards.get(ix))
.map(|card| card.name.clone())
.collect()
}
/// The cards shown, in order.
#[cfg(test)]
pub(crate) fn shown_cards(&self) -> Vec<Card> {
self.shown
.iter()
.filter_map(|&ix| self.cards.get(ix))
.cloned()
.collect()
}
/// The card under the pointer or the keyboard.
pub fn hovered(&self) -> Option<u32> {
self.hovered
}
/// The portraits its cards show, for a card drawn over it.
pub fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
/// Where its visible cards were drawn last.
pub fn drawn_cards(&self) -> &DrawnCards {
&self.drawn_cards
}
/// All its cards, which `DrawnCard::ix` indexes.
pub fn cards(&self) -> &Rc<[Card]> {
&self.cards
}
/// A grid as tall as its rows: the hand of a champ select.
pub fn is_hand(&self) -> bool {
self.fit_content
}
/// How far the grid is scrolled down.
#[cfg(test)]
pub(crate) fn scrolled(&self) -> Pixels {
-self.scroll.0.borrow().base_handle.offset().y
}
fn row(&mut self, ix: usize, metrics: Metrics, cx: &mut Context<Self>) -> AnyElement {
let start = ix * metrics.columns;
// The id and index of the card in each slot, for the row to record where it drew them.
let mut in_slots = [None; MAX_COLUMNS];
let mut slots = Vec::with_capacity(metrics.columns);
for (column, slot) in (start..start + metrics.columns).enumerate() {
// A stale index shows nothing rather than panicking.
let shown = self.shown.get(slot).copied();
match shown.and_then(|c| Some((c, self.cards.get(c)?))) {
Some((c, data)) => {
#[cfg(test)]
{
self.card_builds += 1;
}
let id = data.id;
in_slots[column] = Some((id, c));
let focus = self.focus.get(&id).map(|focus| &focus.handle);
// In the hand, a card an ally took rests a little lower than the others.
let lowered = self.is_hand() && data.reasons.contains(&Reason::TakenByAlly);
slots.push(
card(data, focus, cx)
.when(lowered, |card| card.top(px(TAKEN_DROP)))
.on_hover(cx.listener(move |grid, hovered: &bool, _, cx| {
grid.set_hovered(id, *hovered, cx)
}))
.into_any_element(),
);
}
// The last row keeps every card the same width.
None => slots.push(div().flex_1().min_w_0().into_any_element()),
}
}
let drawn_cards = self.drawn_cards.clone();
div()
.h_flex()
.items_start()
.w_full()
.h(px(metrics.card_height + metrics.gap))
.pb(px(metrics.gap))
// The lane of the list's scrollbar; the page's column leaves its own to the grids it
// scrolls.
.pr(if self.fit_content || self.paged.is_some() {
Pixels::ZERO
} else {
Scrollbar::width()
})
.gap(px(metrics.gap))
// Only a row painted is laid out here, not one `uniform_list` merely measures.
.on_children_prepainted(move |bounds, window, _| {
let visible = window.content_mask().bounds;
let mut drawn_cards = drawn_cards.borrow_mut();
for (slot, bounds) in in_slots.iter().zip(bounds) {
if let Some((id, ix)) = *slot {
drawn_cards.insert(
id,
DrawnCard {
bounds,
visible,
ix,
},
);
}
}
})
.children(slots)
.into_any_element()
}
}
impl CardGrid {
/// The grid's key context, its portraits and what it reacts to besides its cards.
fn with_cards_behaviour(
&self,
root: Div,
images: Entity<CardImages>,
cx: &mut Context<Self>,
) -> Div {
card_images::provide(root, images)
.key_context(CONTEXT)
// A wheel scroll moves cards under a still pointer without a hover event: the
// sheet of the card that was under it would stay. The next mouse move hovers again.
.on_scroll(cx.listener(|grid, _: &ScrollEvent, _, cx| {
// The list has scrolled first. A grid that fits its content, or that the page
// scrolls, is moved by its parent's scrolling instead, which it cannot see.
let moved = grid.fit_content
|| grid.paged.is_some()
|| grid.scrolled_to() != grid.drawn_scroll;
if moved {
grid.hover(None, cx);
}
// Even at either end of the list, no card stays lifted after a wheel; one that
// stays under the pointer keeps its tick lit.
cx.emit(PutDown);
}))
.on_action(cx.listener(|grid, _: &NextCard, window, cx| grid.move_focus(1, window, cx)))
.on_action(
cx.listener(|grid, _: &PreviousCard, window, cx| grid.move_focus(-1, window, cx)),
)
}
}
impl Render for CardGrid {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
if self.focus_stale {
self.sync_focus(window, cx);
}
self.drawn_scroll = self.scrolled_to();
// Only the rows drawn now place their cards.
self.drawn_cards.borrow_mut().clear();
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
if self.shown.is_empty() {
let muted = cx.theme().muted_foreground;
return div()
.w_full()
.debug_selector(|| "no-champion".into())
.py(px(30.))
.text_color(muted)
.child("Aucun champion trouvé")
.into_any_element();
}
let metrics = Metrics::of(window.viewport_size().width);
let rows = self.shown.len().div_ceil(metrics.columns);
if self.fit_content {
// The same rows and cards (sheet, hover, keyboard focus), all built, as a column.
let rows: Vec<_> = (0..rows).map(|ix| self.row(ix, metrics, cx)).collect();
return self
.with_cards_behaviour(div().v_flex().w_full(), images, cx)
.children(rows)
.into_any_element();
}
if let Some(paging) = self.paged.clone() {
// Read now, not when the page was drawn: the page's scrolling has been held within its
// content since. Not laid out yet, the grid is taken to start at the top of the window,
// where the header clicked to open it leaves it: the next frame knows.
let scrolled = -paging.scroll.offset().y;
let last_height = paging.scroll.bounds().size.height;
let viewport = if last_height > Pixels::ZERO {
last_height
} else {
window.viewport_size().height
};
let top = paging.top.get().unwrap_or(scrolled);
let in_view = rows_in_view(rows, px(metrics.row_height()), top, scrolled, viewport);
// Rows that are not in view are left out, as a space above the first one built.
let space = px(metrics.row_height() * in_view.start as f32);
let rows: Vec<_> = in_view.map(|ix| self.row(ix, metrics, cx)).collect();
return self
.with_cards_behaviour(div().v_flex().w_full(), images, cx)
.debug_selector(|| "card-list".into())
.pt(space)
.children(rows)
.into_any_element();
}
self.with_cards_behaviour(div().relative().size_full(), images, cx)
.debug_selector(|| "card-list".into())
.child(
uniform_list(
"cards",
rows,
cx.processor(move |grid, range: Range<usize>, _, cx| {
range
.map(|ix| grid.row(ix, metrics, 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)),
)
.into_any_element()
}
}
#[cfg(test)]
mod tests;
+112
View File
@@ -0,0 +1,112 @@
//! The grid's keyboard: each card has a focus handle, and Tab and Shift-Tab move between the
//! cards, bringing the row of the one reached into view.
use gpui_kit::*;
use super::geometry::Metrics;
use super::{CardGrid, RevealRow};
use crate::card::Card;
actions!(card_grid, [NextCard, PreviousCard]);
/// The grid's key context, where Tab and Shift-Tab move between its cards.
pub(super) const CONTEXT: &str = "CardGrid";
/// Binds Tab and Shift-Tab in the grid's context, where they win over gpui-kit's root: the
/// rows are virtual, so the next card may not be built yet and the root cannot reach it.
pub fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("tab", NextCard, Some(CONTEXT)),
KeyBinding::new("shift-tab", PreviousCard, Some(CONTEXT)),
]);
}
/// What makes one card reachable with the keyboard: its handle, and the subscriptions that lift
/// it while the keyboard is on it.
pub(super) struct CardFocus {
pub(super) handle: FocusHandle,
_subscriptions: [Subscription; 2],
}
impl CardGrid {
/// Gives every card a focus handle, reusing the ones of the ids already there. It runs when
/// the grid is drawn after `set_cards`, as subscribing needs the window.
pub(super) fn sync_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.focus_stale = false;
let mut previous = std::mem::take(&mut self.focus);
for card in self.cards.iter() {
let id = card.id;
let focus = previous.remove(&id).unwrap_or_else(|| {
let handle = cx.focus_handle().tab_stop(true);
// As `:focus-visible`: a card focused by a click is already under the pointer.
let gained = cx.on_focus_in(&handle, window, move |grid, window, cx| {
if window.last_input_was_keyboard() {
grid.hover_by(Some(id), true, cx);
// Tab came from outside the grid too: the page is to show the card.
let position = grid.position_of(id);
grid.reveal_in_page(position, window, cx);
}
});
let lost = cx.on_focus_out(&handle, window, move |grid, _, _, cx| {
grid.set_hovered(id, false, cx);
});
CardFocus {
handle,
_subscriptions: [gained, lost],
}
});
self.focus.insert(id, focus);
}
}
/// Moves the focus `step` cards on in the grid's order, scrolling its row into view since
/// only the visible rows are built (a paged grid asks the page to). At either end the key
/// goes on, to leave the grid.
pub(super) fn move_focus(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
let focused = |card: &Card| {
self.focus
.get(&card.id)
.is_some_and(|focus| focus.handle.is_focused(window))
};
let current = self
.shown
.iter()
.position(|&ix| self.cards.get(ix).is_some_and(focused));
let target = current
.and_then(|current| current.checked_add_signed(step))
.filter(|&target| target < self.shown.len());
let handle = target.and_then(|target| {
let card = self.cards.get(*self.shown.get(target)?)?;
Some((target, self.focus.get(&card.id)?.handle.clone()))
});
let Some((target, handle)) = handle else {
cx.propagate();
return;
};
if self.paged.is_some() {
self.reveal_in_page(Some(target), window, cx);
} else if !self.fit_content {
let columns = Metrics::of(window.viewport_size().width).columns;
self.scroll
.scroll_to_item(target / columns, ScrollStrategy::Nearest);
}
window.focus(&handle, cx);
}
/// Where the card with this id is among the cards shown.
fn position_of(&self, id: u32) -> Option<usize> {
let is_it = |&ix: &usize| self.cards.get(ix).is_some_and(|card| card.id == id);
self.shown.iter().position(is_it)
}
/// A paged grid asks the page to scroll to the row of the card at this position.
fn reveal_in_page(&mut self, position: Option<usize>, window: &Window, cx: &mut Context<Self>) {
let (Some(position), true) = (position, self.paged.is_some()) else {
return;
};
let metrics = Metrics::of(window.viewport_size().width);
let top = px(metrics.row_height() * (position / metrics.columns) as f32);
let bottom = top + px(metrics.card_height);
cx.emit(RevealRow { top, bottom });
}
}
+83
View File
@@ -0,0 +1,83 @@
use gpui_kit::Pixels;
use gpui_kit::component::scroll::Scrollbar;
use crate::card::ASPECT;
use crate::page::PAGE_PADDING;
/// The widest content column of the home, as in the mockup.
pub const MAX_WIDTH: f32 = 1264.;
/// How much lower than the others a card of the hand taken by an ally rests (#87).
pub const TAKEN_DROP: f32 = 8.;
/// The most cards a row holds.
pub(super) const MAX_COLUMNS: usize = 6;
/// How many cards fit a row of a window `width` wide, with the mockup's breakpoints: its
/// `max-width` rules apply up to and including 1000, 720 and 480 px.
pub(super) fn columns(width: Pixels) -> usize {
match width.as_f32() {
w if w > 1000. => MAX_COLUMNS,
w if w > 720. => 4,
w if w > 480. => 3,
_ => 2,
}
}
/// Smaller gaps in the narrow layouts, as in the mockup.
fn gap(columns: usize) -> f32 {
if columns >= 4 { 14. } else { 10. }
}
/// What a frame needs to know, from the window width alone: `uniform_list` measures its first
/// row without knowing the list's width, so the row height cannot come from the layout.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Metrics {
pub(super) columns: usize,
pub(super) gap: f32,
/// A card's height; a row is this plus a gap tall.
pub(super) card_height: f32,
}
impl Metrics {
pub(super) fn of(window_width: Pixels) -> Metrics {
let columns = columns(window_width);
let gap = gap(columns);
// The column the page centres, minus the scrollbar's lane.
let content = (window_width.as_f32() - 2. * PAGE_PADDING).min(MAX_WIDTH)
- Scrollbar::width().as_f32();
let card_width = (content - gap * (columns - 1) as f32) / columns as f32;
Metrics {
columns,
gap,
card_height: (card_width / ASPECT).max(0.),
}
}
/// What one row of the list takes: a card and the gap under it.
pub(super) fn row_height(&self) -> f32 {
self.card_height + self.gap
}
}
/// Which rows of a grid of `rows` rows, `row_height` tall each, a viewport shows: the grid's top
/// is `top` down the scrolled content, which is scrolled `scrolled`, and the viewport is
/// `viewport` tall. A row shown in part counts. A grid wholly below the window keeps its first
/// row built: the keyboard enters the grid there (Tab from the search), and the page scrolls to it.
pub(super) fn rows_in_view(
rows: usize,
row_height: Pixels,
top: Pixels,
scrolled: Pixels,
viewport: Pixels,
) -> std::ops::Range<usize> {
let row_height = row_height.as_f32().max(1.);
let above = (scrolled - top).as_f32();
let below = above + viewport.as_f32();
if below <= 0. {
return 0..rows.min(1);
}
let first = ((above.max(0.) / row_height).floor() as usize).min(rows);
let last = ((below.max(0.) / row_height).ceil() as usize).min(rows);
first..last.max(first)
}
+48
View File
@@ -0,0 +1,48 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use gpui_kit::{Bounds, Pixels, ScrollHandle};
/// The card under the pointer, or the one the keyboard is on, changed: its id, or none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CardHovered {
pub id: Option<u32>,
/// The keyboard brought it: the pointer moving puts it down.
pub by_keyboard: bool,
}
/// None of the grid's cards stays lifted, at once: a wheel turned over them, or they are no
/// longer shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PutDown;
/// What a grid the page scrolls reads to know which of its rows are in view: the page's scrolling
/// and where the grid starts in it.
#[derive(Clone)]
pub struct Paging {
pub scroll: ScrollHandle,
/// How far down the scrolled content the grid starts, as its last layout put it; none until
/// it was laid out.
pub top: Rc<Cell<Option<Pixels>>>,
}
/// The keyboard went to a card of a paged grid, whose scrolling is the page's: this row, as
/// the distances of its top and its bottom from the grid's top, is to be scrolled into view.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RevealRow {
pub top: Pixels,
pub bottom: Pixels,
}
/// Where the grid last drew a card, in the window, the part of the window it showed of it, and
/// its index in the grid's cards.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DrawnCard {
pub bounds: Bounds<Pixels>,
pub visible: Bounds<Pixels>,
pub ix: usize,
}
/// The cards the grid drew last, by id: filled as its rows are laid out, read between its draws.
pub type DrawnCards = Rc<RefCell<HashMap<u32, DrawnCard>>>;
+55
View File
@@ -0,0 +1,55 @@
use gpui_kit::px;
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::geometry::{Metrics, columns, rows_in_view};
use crate::card::ASPECT;
#[test]
fn the_columns_follow_the_mockups_breakpoints() {
for (width, expected) in [
(2560., 6),
(1280., 6),
(1001., 6),
(1000., 4),
(721., 4),
(720., 3),
(481., 3),
(480., 2),
(300., 2),
] {
assert_eq!(columns(px(width)), expected, "{width} px");
}
}
#[test]
fn the_rows_in_view_are_those_the_window_shows_even_in_part() {
// 10 rows of 100 px, the grid starting 250 px down the content, in a 400 px window.
let rows = |scrolled: f32| rows_in_view(10, px(100.), px(250.), px(scrolled), px(400.));
// Above it: the window ends 150 px into the grid, in its second row.
assert_eq!(rows(0.), 0..2);
assert_eq!(rows(100.), 0..3);
// Inside it: the rows cut by either edge count.
assert_eq!(rows(400.), 1..6);
// Wholly below the window: its first row, for the keyboard to enter by.
assert_eq!(rows_in_view(10, px(100.), px(900.), px(0.), px(400.)), 0..1);
// Past its end: nothing.
assert_eq!(rows(2000.), 10..10);
// No row.
assert_eq!(rows_in_view(0, px(100.), px(0.), px(0.), px(400.)), 0..0);
}
#[test]
fn the_cards_fill_the_column_the_page_centres() {
use gpui_kit::component::scroll::Scrollbar;
for (window, column) in [(1280., 1256.), (3000., 1264.), (800., 776.), (500., 476.)] {
let metrics = Metrics::of(px(window));
let card_width = metrics.card_height * ASPECT;
let row = card_width * metrics.columns as f32
+ metrics.gap * (metrics.columns - 1) as f32
+ Scrollbar::width().as_f32();
assert!(
(row - column).abs() < 0.01,
"{window} px: {row} vs {column}"
);
}
}
+156
View File
@@ -0,0 +1,156 @@
//! The portraits of a card grid: decoded only for the cards it paints, and freed, in memory and
//! on the GPU, once it paints them no more (rule #1: memory in proportion to what is shown). The
//! champion table holds its rows' portraits the same way.
//!
//! Each grid owns one `CardImages`, which its cards' `img` elements read through (`provide`),
//! never through GPUI's app-wide asset cache, which keeps every image it ever loaded. A grid may
//! be a cached view: while it is not rendered again, its last paint is replayed with the images
//! it used. So the cache only changes in the grid's own render: each one starts with
//! `start_render`, which drops what the previous render did not paint, as no frame shows it.
use std::collections::HashMap;
use std::sync::Arc;
use gpui_kit::*;
struct Entry {
/// The image, or its load while it runs, or why it failed.
item: ImageCacheItem,
/// The last render that painted it.
painted: u64,
}
pub struct CardImages {
entries: HashMap<Resource, Entry>,
/// The grid's render being drawn.
render: u64,
/// The grid is painting: `uniform_list` also lays rows out only to measure them, and a row
/// that is not painted is not shown, so its portraits are neither loaded nor kept.
painting: bool,
/// Loads started, to guard against retrying a failed one every frame.
#[cfg(test)]
pub(crate) loads: usize,
}
impl CardImages {
pub fn new(cx: &mut App) -> Entity<CardImages> {
let images = cx.new(|_| CardImages {
entries: HashMap::new(),
render: 0,
painting: false,
#[cfg(test)]
loads: 0,
});
// The grid is gone: so are its portraits, from every window's atlas too.
cx.observe_release(&images, |images, cx| {
for (_, entry) in images.entries.drain() {
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, None);
}
}
})
.detach();
images
}
/// Drops every portrait, in memory and in the window's atlas, for a grid that is no longer
/// shown: they load again when it is drawn. A load still running is cancelled. True when
/// something was held.
pub fn release(&mut self, window: &mut Window, cx: &mut App) -> bool {
let held = !self.entries.is_empty();
for (_, entry) in self.entries.drain() {
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, Some(window));
}
}
held
}
/// Called first in each render of the grid. The frame on screen shows what the previous
/// render painted, and the frame being drawn shows only what this one will paint: anything
/// else is dropped, in memory and in the window's atlas. A load still running is cancelled.
pub fn start_render(&mut self, window: &mut Window, cx: &mut App) {
let previous = self.render;
self.entries.retain(|_, entry| {
if entry.painted == previous {
return true;
}
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, Some(window));
}
false
});
self.render += 1;
self.painting = false;
}
}
impl ImageCache for CardImages {
/// While the grid lays out, an image already there is given back and nothing is loaded.
/// While it paints, a missing image starts loading off the UI thread, and its end draws the
/// grid again. A failed load is kept, so it is not tried again while the card stays shown.
fn load(
&mut self,
resource: &Resource,
window: &mut Window,
cx: &mut App,
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
if !self.painting {
return self
.entries
.get(resource)
.and_then(|entry| entry.item.get());
}
let render = self.render;
let entry = self.entries.entry(resource.clone()).or_insert_with(|| {
#[cfg(test)]
{
self.loads += 1;
}
Entry {
item: ImageCacheItem::new(resource, cx),
painted: render,
}
});
entry.painted = render;
entry.item.use_image(window)
}
}
/// `root`, whose `img` elements read through `images`. `root` gets its children after this:
/// a mark painted before them tells `images` that the grid paints.
pub fn provide(root: Div, images: Entity<CardImages>) -> Div {
let painting = images.clone();
root.image_cache(images).child(
canvas(
|_, _, _| {},
move |_, _, _, cx| painting.update(cx, |images, _| images.painting = true),
)
.absolute(),
)
}
#[cfg(test)]
impl CardImages {
/// The portraits held, loaded or not, sorted.
pub(crate) fn held(&self) -> Vec<std::path::PathBuf> {
let mut paths: Vec<_> = (self.entries.keys())
.filter_map(|resource| match resource {
Resource::Path(path) => Some(path.to_path_buf()),
_ => None,
})
.collect();
paths.sort();
paths
}
/// The images decoded.
pub(crate) fn loaded(&self) -> Vec<Arc<RenderImage>> {
(self.entries.values())
.filter_map(|entry| entry.item.get()?.ok())
.collect()
}
}
#[cfg(test)]
pub(crate) mod tests;
+298
View File
@@ -0,0 +1,298 @@
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use arena_tracker_core::Marks;
use gpui_kit::{
AppContext as _, Bounds, Context, Entity, ImageSource, InteractiveElement as _, IntoElement,
Modifiers, ParentElement as _, Render, RenderImage, ScrollDelta, ScrollEvent, StyleRefinement,
Styled as _, TestAppContext, VisualTestContext, Window, WindowBounds, WindowOptions, div,
point, px, red, size,
};
use super::CardImages;
use crate::card::Card;
use crate::card_grid::CardGrid;
/// A 68 x 100 JPEG, as the core stores the card portraits (smaller).
pub(crate) const PORTRAIT_JPEG: &[u8] = include_bytes!("../../tests/fixtures/portrait.jpg");
/// A folder of its own in the system's temporary folder, removed with the value.
pub(crate) struct TestDir(PathBuf);
impl TestDir {
pub(crate) fn new(name: &str) -> TestDir {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let path = std::env::temp_dir().join(format!(
"arena-tracker-{name}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
TestDir(path)
}
pub(crate) fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A bar with a button, as the page's header, above the grid as the home has it: cached.
struct Host {
grid: Option<Entity<CardGrid>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.flex_col()
.child(
div().h(px(60.)).flex_shrink_0().child(
div()
.id("outside")
.debug_selector(|| "outside".into())
.w(px(200.))
.h_full()
.hover(|style| style.bg(red())),
),
)
.children(self.grid.clone().map(|grid| {
grid.cached(StyleRefinement::default().w_full().flex_1().min_h(px(240.)))
}))
}
}
fn portrait(dir: &Path, id: u32) -> PathBuf {
dir.join(format!("{id}.jpg"))
}
/// A 1280 x 860 window, as the page tests', on `count` cards whose portraits are in `dir`,
/// written there when `write`.
fn open_grid(
cx: &mut TestAppContext,
dir: &Path,
count: u32,
write: bool,
) -> (Entity<Host>, Entity<CardGrid>, VisualTestContext) {
cx.update(gpui_kit::init);
let cards: Rc<[Card]> = (1..=count)
.map(|id| {
let path = portrait(dir, id);
if write {
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
}
Card {
id,
name: format!("Champion {id:03}").into(),
portrait: Some(path.into()),
marks: Marks {
played: false,
won: false,
completed: false,
},
reasons: Vec::new(),
sheet: Vec::new(),
}
})
.collect();
let (window, host) = cx.update(|cx| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
})),
..Default::default()
};
gpui_kit::open_window(options, cx, |_, cx| {
let grid = cx.new(|cx| {
let mut grid = CardGrid::new();
grid.set_cards(cards, cx);
grid.set_shown((0..count as usize).collect(), cx);
grid
});
cx.new(|_| Host { grid: Some(grid) })
})
.unwrap()
});
let grid = cx.read(|cx| host.read(cx).grid.clone().unwrap());
(host, grid, VisualTestContext::from_window(window, cx))
}
fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Draws, lets the started loads end, and draws what they drew again.
fn draw_loaded(cx: &mut VisualTestContext) {
draw(cx);
cx.run_until_parked();
draw(cx);
}
fn images(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) -> Entity<CardImages> {
grid.read_with(cx, |grid, _| grid.images().cloned())
.expect("the grid was not rendered")
}
/// The ids of the cards drawn in the last frame.
fn drawn(cx: &mut VisualTestContext, count: u32) -> Vec<u32> {
(1..=count)
.filter(|id| {
cx.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
.is_some()
})
.collect()
}
fn portraits(dir: &Path, ids: &[u32]) -> Vec<PathBuf> {
let mut paths: Vec<_> = ids.iter().map(|&id| portrait(dir, id)).collect();
paths.sort();
paths
}
fn in_atlas(cx: &mut VisualTestContext, image: &RenderImage) -> bool {
cx.update(|window, _| window.has_image_atlas_entry(image))
}
fn scroll(cx: &mut VisualTestContext, by: f32) {
cx.simulate_event(ScrollEvent {
position: point(px(640.), px(400.)),
delta: ScrollDelta::Pixels(point(px(0.), px(by))),
..Default::default()
});
}
#[gpui::test]
fn only_the_portraits_of_the_drawn_cards_are_kept(cx: &mut TestAppContext) {
let dir = TestDir::new("drawn-portraits");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
let cx = &mut window;
draw_loaded(cx);
let top = drawn(cx, 170);
// A few rows of 6, not the 170 cards; the first row is measured on every render, and
// its portraits are not kept for that.
assert!(top.contains(&1) && top.len() <= 6 * 4, "{top:?}");
let images = images(&grid, cx);
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &top)
);
let first = images.read_with(cx, |images, _| images.loaded());
assert_eq!(first.len(), top.len(), "the portraits were not decoded");
assert!(first.iter().all(|image| in_atlas(cx, image)));
// Never through the app-wide asset cache, which would keep them.
cx.update(|_, cx| {
for &id in &top {
let source = ImageSource::from(portrait(dir.path(), id));
assert!(!source.is_asset_cached(cx), "card {id}");
}
});
// To the end: the last rows' portraits are loaded, and the first rows' ones are dropped,
// from the GPU atlas too.
scroll(cx, -100_000.);
draw_loaded(cx);
let bottom = drawn(cx, 170);
assert!(bottom.contains(&170) && !bottom.contains(&1), "{bottom:?}");
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &bottom)
);
assert_eq!(
images.read_with(cx, |images, _| images.loaded()).len(),
bottom.len()
);
assert!(first.iter().all(|image| !in_atlas(cx, image)));
// Back to the top: loaded again.
let loads = images.read_with(cx, |images, _| images.loads);
scroll(cx, 100_000.);
draw_loaded(cx);
assert_eq!(drawn(cx, 170), top);
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &top)
);
assert_eq!(
images.read_with(cx, |images, _| images.loads),
loads + top.len()
);
}
// The grid is a cached view: a frame that replays its last paint must keep its images.
#[gpui::test]
fn hovering_outside_the_grid_drops_no_portrait(cx: &mut TestAppContext) {
let dir = TestDir::new("hover-outside");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
let cx = &mut window;
draw_loaded(cx);
let images = images(&grid, cx);
let held = images.read_with(cx, |images, _| images.held());
let loaded = images.read_with(cx, |images, _| images.loaded());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(!loaded.is_empty());
let button = cx.debug_bounds("outside").unwrap().center();
for _ in 0..2 {
cx.simulate_mouse_move(button, None, Modifiers::none());
draw(cx);
cx.simulate_mouse_move(point(px(1000.), px(30.)), None, Modifiers::none());
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
assert_eq!(images.read_with(cx, |images, _| images.held()), held);
assert!(loaded.iter().all(|image| in_atlas(cx, image)));
}
#[gpui::test]
fn a_missing_portrait_leaves_the_card_readable_and_is_tried_once(cx: &mut TestAppContext) {
let dir = TestDir::new("missing-portraits");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 30, false);
let cx = &mut window;
draw_loaded(cx);
let shown = drawn(cx, 30);
assert!(shown.contains(&1), "{shown:?}");
let images = images(&grid, cx);
assert!(images.read_with(cx, |images, _| images.loaded()).is_empty());
let loads = images.read_with(cx, |images, _| images.loads);
assert_eq!(loads, shown.len());
// Drawing the grid again, as a hover over its cards does, tries none of them again.
for _ in 0..3 {
grid.update(cx, |_, cx| cx.notify());
draw_loaded(cx);
}
assert_eq!(drawn(cx, 30), shown);
assert_eq!(images.read_with(cx, |images, _| images.loads), loads);
}
#[gpui::test]
fn the_portraits_are_freed_with_their_grid(cx: &mut TestAppContext) {
let dir = TestDir::new("freed-portraits");
let (host, grid, mut window) = open_grid(cx, dir.path(), 30, true);
let cx = &mut window;
draw_loaded(cx);
let loaded: Vec<Arc<RenderImage>> =
images(&grid, cx).read_with(cx, |images, _| images.loaded());
assert!(!loaded.is_empty());
assert!(loaded.iter().all(|image| in_atlas(cx, image)));
host.update(cx, |host, cx| {
host.grid = None;
cx.notify();
});
drop(grid);
draw(cx);
cx.run_until_parked();
assert!(loaded.iter().all(|image| !in_atlas(cx, image)));
}
+366
View File
@@ -0,0 +1,366 @@
//! The lift of the card under the pointer or the keyboard (#88): which cards are lifted, and how
//! far, in each grid. A card rises when the pointer or the keyboard comes to it and settles back
//! when it leaves, each time from where it is; in the hand, a veil lays on the other cards.
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use crate::card::{CARD_RADIUS, Card, MarkFill, Pose, lifted, veil_color};
use crate::card_grid::{DrawnCard, DrawnCards};
use crate::card_images::CardImages;
use crate::motion::{MATCH_SETTLE, ease_out};
/// How long a card takes to rise all the way, or to settle back.
const RISE: Duration = Duration::from_millis(350);
/// How long the hand's veil takes to lay on its cards, or to lift.
const VEIL: Duration = Duration::from_millis(300);
/// A value moving to `to`, from where it was when asked to.
#[derive(Clone, Copy, Debug)]
struct Tween {
from: f32,
to: f32,
start: Instant,
duration: Duration,
}
impl Tween {
fn value(&self, now: Instant) -> f32 {
self.from + (self.to - self.from) * ease_out(self.progress(now))
}
fn progress(&self, now: Instant) -> f32 {
if self.duration.is_zero() {
return 1.;
}
let elapsed = now.saturating_duration_since(self.start);
(elapsed.as_secs_f32() / self.duration.as_secs_f32()).min(1.)
}
fn done(&self, now: Instant) -> bool {
self.progress(now) >= 1.
}
/// Towards `to` from where it is now, over the part of `full` that is left to go.
fn toward(&self, to: f32, full: Duration, now: Instant) -> Tween {
let from = self.value(now);
Tween {
from,
to,
start: now,
duration: full.mul_f32((to - from).abs()),
}
}
fn rest(value: f32, now: Instant) -> Tween {
Tween {
from: value,
to: value,
start: now,
duration: Duration::ZERO,
}
}
}
/// A card lifted, or settling back, over grid `G`.
struct Entry<G> {
grid: G,
id: u32,
lift: Tween,
}
/// A card as it is drawn now: `progress` is 0 at rest and 1 lifted all the way.
pub(crate) struct Lifted {
pub id: u32,
pub progress: f32,
}
/// Which cards are lifted, by id: what they show is the grid's card as it is when drawn.
pub(crate) struct Lifts<G> {
/// In paint order: the card rising last.
cards: Vec<Entry<G>>,
/// The veil of each hand, while it is not lifted.
veils: Vec<(G, Tween)>,
}
impl<G: Copy + PartialEq> Lifts<G> {
pub fn new() -> Self {
Lifts {
cards: Vec::new(),
veils: Vec::new(),
}
}
/// The card under the pointer or the keyboard in `grid` is now `id`, or none: it rises,
/// and the one it replaces in that grid settles back.
/// In a hand (`veiled`), a veil lays on its other cards while one is lifted.
pub fn hover(&mut self, grid: G, id: Option<u32>, veiled: bool, now: Instant) {
if veiled {
let to = if id.is_some() { 1. } else { 0. };
match self.veils.iter_mut().find(|(hand, _)| *hand == grid) {
Some((_, veil)) if veil.to != to => *veil = veil.toward(to, VEIL, now),
Some(_) => {}
None => self
.veils
.push((grid, Tween::rest(0., now).toward(to, VEIL, now))),
}
}
for entry in self.cards.iter_mut() {
if entry.grid == grid && Some(entry.id) != id && entry.lift.to != 0. {
entry.lift = entry.lift.toward(0., RISE, now);
}
}
if let Some(id) = id {
// A card settling back rises again from where it is, drawn over the others.
let settling =
(self.cards.iter()).position(|entry| entry.grid == grid && entry.id == id);
let lift = match settling.map(|ix| self.cards.remove(ix)) {
Some(entry) if entry.lift.to == 1. => entry.lift,
Some(entry) => entry.lift.toward(1., RISE, now),
None => Tween::rest(0., now).toward(1., RISE, now),
};
self.cards.push(Entry { grid, id, lift });
}
}
/// The cards of `grid` moved under a still pointer (a wheel): none stays lifted, nor does
/// its veil, at once.
pub fn drop_grid(&mut self, grid: G) {
self.cards.retain(|entry| entry.grid != grid);
self.veils.retain(|(hand, _)| *hand != grid);
}
/// No card lifted any more, at once: the grids are no longer shown.
pub fn clear(&mut self) {
self.cards.clear();
self.veils.clear();
}
/// Every card and veil where it was going, at once: nothing to animate.
pub fn finish(&mut self, now: Instant) {
for entry in self.cards.iter_mut() {
entry.lift = Tween::rest(entry.lift.to, now);
}
for (_, veil) in self.veils.iter_mut() {
*veil = Tween::rest(veil.to, now);
}
self.tidy(now);
}
/// Forgets the cards back at rest: they are the grid's own again.
pub fn tidy(&mut self, now: Instant) {
self.cards
.retain(|entry| !(entry.lift.to == 0. && entry.lift.done(now)));
self.veils
.retain(|(_, veil)| !(veil.to == 0. && veil.done(now)));
}
/// Whether a card still moves.
pub fn animating(&self, now: Instant) -> bool {
self.cards.iter().any(|entry| !entry.lift.done(now))
|| self.veils.iter().any(|(_, veil)| !veil.done(now))
}
/// How far the veil lays on the cards of `grid`, 0 to 1.
pub fn veil(&self, grid: G, now: Instant) -> f32 {
(self.veils.iter())
.find(|(hand, _)| *hand == grid)
.map_or(0., |(_, veil)| veil.value(now))
}
/// The cards of `grid` to draw over it, in paint order.
pub fn lifted(&self, grid: G, now: Instant) -> impl Iterator<Item = Lifted> + '_ {
self.cards
.iter()
.filter(move |entry| entry.grid == grid)
.map(move |entry| Lifted {
id: entry.id,
progress: entry.lift.value(now),
})
}
}
/// The card of the champion a followed Match has just changed, drawn over its grid like a lifted
/// one at rest while it changes in place (#89).
pub(crate) struct Changing {
/// The card before the Match.
pub before: Rc<Card>,
/// Seconds since the comet landed (since the start without one): negative while it flies.
pub since_landing: f32,
}
/// A lifted card of the hand an ally just took (`stage::Taken`): it goes down to its place as
/// it greys, the card as it was fading over it.
pub(crate) struct Lowered {
pub id: u32,
/// How far above its place it still is.
pub above: f32,
pub before: Rc<Card>,
/// The opacity of the card as it was.
pub opacity: f32,
}
/// What changes on the lifted cards of a grid as they are drawn: the card of the home a followed
/// Match changes (#89), or the cards of the hand an ally just took (#87).
pub(crate) enum Changes {
Match(Changing),
Taken(Vec<Lowered>),
}
/// Draws the lifted cards of a grid over it, `lifted` in paint order with how far each is, and
/// the hand's `veil` over the others, where the grid last placed them and as `cards` holds them
/// now: the grid is not drawn again, and the pointer still meets its cards. Painted after the
/// rest of the page, so a card rises over what is above it; a card the grid shows only in part
/// stays cut where it is. The cards `changes` names show their change.
pub(crate) fn layer(
cards: Rc<[Card]>,
drawn_cards: DrawnCards,
images: Option<Entity<CardImages>>,
lifted_cards: Vec<Lifted>,
changes: Changes,
veil: f32,
moves: bool,
) -> AnyElement {
deferred(
canvas(
move |_, window, cx| {
let drawn_cards = drawn_cards.borrow();
let background = cx.theme().background;
let mut layers = Vec::new();
if veil > 0. {
for (id, drawn) in drawn_cards.iter() {
if !lifted_cards.iter().any(|lifted| lifted.id == *id) {
layers.push(Layer::Quad(drawn.bounds, veil_color(veil), drawn.visible));
}
}
}
for &Lifted { id, progress } in &lifted_cards {
let drawn = drawn_cards.get(&id);
let card = drawn.and_then(|drawn| cards.get(drawn.ix));
let (Some(drawn), Some(card)) = (drawn, card) else {
continue;
};
let change = match &changes {
Changes::Match(change) if change.before.id == id => Some(change),
_ => None,
};
// The card as it was until the comet lands.
let card = change
.filter(|c| c.since_landing < 0.)
.map_or(card, |c| c.before.as_ref());
let pose = Pose {
mark_fill: change.map(|c| MarkFill {
before: c.before.marks,
progress: (c.since_landing / MATCH_SETTLE).clamp(0., 1.),
}),
progress,
// Settling back, it goes under the veil of the cards at rest.
veil: veil * (1. - progress),
moves,
};
// Its place in the grid, where the card at rest is not to be seen.
layers.push(Layer::Quad(drawn.bounds, background, drawn.visible));
let mask = cut(drawn).map(|bounds| ContentMask { bounds });
let lowered = match &changes {
Changes::Taken(lowered) => lowered.iter().find(|lowered| lowered.id == id),
Changes::Match(_) => None,
};
let above = lowered.map_or(0., |lowered| lowered.above);
let size = drawn.bounds.size;
let before = lowered
.filter(|lowered| lowered.opacity > 0.)
.map(|lowered| {
let before = &*lowered.before;
let element = self::lifted(before, pose, size, cx)
.opacity(lowered.opacity)
.debug_selector(move || format!("lifted-before-{id}"));
(before, element)
});
let now = Some((card, self::lifted(card, pose, size, cx)));
for (card, element) in [now, before].into_iter().flatten() {
let origin =
drawn.bounds.origin - point(px(0.), px(pose.rise(card) + above));
layers.push(prepaint_card(
element,
images.as_ref(),
origin,
size,
mask,
window,
cx,
));
}
}
layers
},
|_, layers, window, cx| paint(layers, window, cx),
)
.absolute(),
)
.into_any_element()
}
/// Where a lifted card is cut: nowhere when its grid shows it whole, so it rises out of a
/// scrolling list, else where the grid cuts it. A fraction of a pixel of layout or scrolling
/// does not cut a card flush with the list's edge.
pub(crate) fn cut(drawn: &DrawnCard) -> Option<Bounds<Pixels>> {
const SLACK: f32 = 1.;
let (card, shown) = (drawn.bounds, drawn.visible);
let whole = card.top().as_f32() >= shown.top().as_f32() - SLACK
&& card.bottom().as_f32() <= shown.bottom().as_f32() + SLACK
&& card.left().as_f32() >= shown.left().as_f32() - SLACK
&& card.right().as_f32() <= shown.right().as_f32() + SLACK;
(!whole).then_some(shown)
}
/// Prepaints `element`, a card of `size` drawn at `origin` over a grid and cut by `mask`, with
/// the grid's `images`.
pub(crate) fn prepaint_card(
mut element: Div,
images: Option<&Entity<CardImages>>,
origin: Point<Pixels>,
size: Size<Pixels>,
mask: Option<ContentMask<Pixels>>,
window: &mut Window,
cx: &mut App,
) -> Layer {
if let Some(images) = images {
element = element.image_cache(images.clone());
}
let mut element = element.into_any_element();
window.with_content_mask(mask, |window| {
element.prepaint_as_root(origin, size.into(), window, cx)
});
Layer::Card(element, mask)
}
/// What a layer over a grid paints, in order.
pub(crate) enum Layer {
/// A rounded quad over a card's place, cut to what the grid shows of it.
Quad(Bounds<Pixels>, Hsla, Bounds<Pixels>),
/// A card prepainted where it is drawn, cut by its mask.
Card(AnyElement, Option<ContentMask<Pixels>>),
}
/// Paints the layers prepainted over a grid, in order.
pub(crate) fn paint(layers: Vec<Layer>, window: &mut Window, cx: &mut App) {
for layer in layers {
match layer {
Layer::Quad(bounds, color, visible) => {
let mask = ContentMask { bounds: visible };
window.with_content_mask(Some(mask), |window| {
window.paint_quad(fill(bounds, color).corner_radii(px(CARD_RADIUS)))
});
}
Layer::Card(mut element, mask) => {
window.with_content_mask(mask, |window| element.paint(window, cx));
}
}
}
}
#[cfg(test)]
mod tests;
+174
View File
@@ -0,0 +1,174 @@
use std::time::{Duration, Instant};
use gpui_kit::{Bounds, point, px, size};
use super::{Lifts, cut};
use crate::card_grid::DrawnCard;
const GRID: u32 = 1;
fn at(start: Instant, ms: u64) -> Instant {
start + Duration::from_millis(ms)
}
fn on(id: u32) -> Option<u32> {
Some(id)
}
fn progress(lifts: &Lifts<u32>, id: u32, now: Instant) -> Option<f32> {
lifts
.lifted(GRID, now)
.find(|lifted| lifted.id == id)
.map(|lifted| lifted.progress)
}
#[test]
fn a_hovered_card_rises_in_350_ms_and_settles_back_in_as_long_once_left() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
assert_eq!(progress(&lifts, 7, start), Some(0.));
let half = progress(&lifts, 7, at(start, 175)).unwrap();
// Fast at first, then settling, as the reference's cubic-bezier(.2, .8, .2, 1).
assert!(half > 0.5 && half < 1., "{half}");
assert_eq!(progress(&lifts, 7, at(start, 350)), Some(1.));
assert!(lifts.animating(at(start, 349)));
assert!(!lifts.animating(at(start, 350)));
lifts.hover(GRID, None, false, at(start, 400));
assert_eq!(progress(&lifts, 7, at(start, 400)), Some(1.));
assert!(progress(&lifts, 7, at(start, 600)).unwrap() > 0.);
assert_eq!(progress(&lifts, 7, at(start, 750)), Some(0.));
// Back at rest, the card is the grid's own again.
lifts.tidy(at(start, 750));
assert_eq!(progress(&lifts, 7, at(start, 750)), None);
assert!(!lifts.animating(at(start, 750)));
}
#[test]
fn a_card_left_or_taken_back_during_its_animation_starts_from_where_it_is() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
let midway = progress(&lifts, 7, at(start, 100)).unwrap();
// Left on its way up: it settles from there, with no jump, and sooner than from the top.
lifts.hover(GRID, None, false, at(start, 100));
assert_eq!(progress(&lifts, 7, at(start, 100)), Some(midway));
let back = at(start, 100 + (350. * midway).ceil() as u64);
assert_eq!(progress(&lifts, 7, back), Some(0.));
// Taken back on its way down: it rises again from there, still one card.
lifts.hover(GRID, on(7), false, at(start, 200));
lifts.hover(GRID, None, false, at(start, 200));
lifts.hover(GRID, on(7), false, at(start, 200));
let low = progress(&lifts, 7, at(start, 200)).unwrap();
assert!(low > 0. && low < midway, "{low}");
assert_eq!(lifts.lifted(GRID, at(start, 200)).count(), 1);
assert_eq!(progress(&lifts, 7, at(start, 550)), Some(1.));
}
#[test]
fn the_card_rising_is_drawn_over_the_one_settling_and_each_grid_keeps_its_own() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
lifts.hover(GRID, on(8), false, at(start, 350));
lifts.hover(GRID, on(7), false, at(start, 400));
let order: Vec<_> = (lifts.lifted(GRID, at(start, 400)))
.map(|lifted| lifted.id)
.collect();
assert_eq!(order, [8, 7]);
// Another grid saying none of its cards is under the pointer leaves this one's.
lifts.hover(2, None, false, at(start, 400));
lifts.hover(2, on(9), false, at(start, 400));
assert_eq!(progress(&lifts, 7, at(start, 750)), Some(1.));
assert_eq!(lifts.lifted(2, at(start, 400)).count(), 1);
}
#[test]
fn in_the_hand_a_veil_lays_on_the_other_cards_while_one_is_lifted() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
assert_eq!(lifts.veil(GRID, start), 0.);
assert!(lifts.veil(GRID, at(start, 150)) > 0.);
assert_eq!(lifts.veil(GRID, at(start, 300)), 1.);
assert!(lifts.animating(at(start, 340)));
// From card to card, it stays.
lifts.hover(GRID, on(8), true, at(start, 400));
assert_eq!(lifts.veil(GRID, at(start, 500)), 1.);
lifts.hover(GRID, None, true, at(start, 800));
assert!(lifts.veil(GRID, at(start, 900)) > 0.);
assert_eq!(lifts.veil(GRID, at(start, 1100)), 0.);
// Elsewhere than in the hand, none.
lifts.hover(2, on(9), false, at(start, 1200));
assert_eq!(lifts.veil(2, at(start, 1600)), 0.);
}
#[test]
fn a_wheel_over_a_grid_drops_its_cards_at_once() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
lifts.hover(2, on(9), false, start);
lifts.drop_grid(GRID);
assert_eq!(lifts.lifted(GRID, start).count(), 0);
assert_eq!(lifts.veil(GRID, start), 0.);
assert_eq!(lifts.lifted(2, start).count(), 1);
}
#[test]
fn finishing_shows_the_end_state_at_once_and_nothing_moves_any_more() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
lifts.hover(GRID, on(8), true, at(start, 100));
lifts.finish(at(start, 100));
assert!(!lifts.animating(at(start, 100)));
assert_eq!(progress(&lifts, 8, at(start, 100)), Some(1.));
// The card left is back at rest, and the grid's own again.
assert_eq!(progress(&lifts, 7, at(start, 100)), None);
assert_eq!(lifts.veil(GRID, at(start, 100)), 1.);
lifts.clear();
assert_eq!(lifts.lifted(GRID, start).count(), 0);
assert_eq!(lifts.veil(GRID, start), 0.);
}
fn drawn_card(top: f32, list_top: f32) -> DrawnCard {
DrawnCard {
bounds: Bounds::new(point(px(12.), px(top)), size(px(240.), px(350.))),
visible: Bounds::new(point(px(12.), px(list_top)), size(px(1256.), px(480.))),
ix: 0,
}
}
#[test]
fn a_card_the_list_shows_whole_rises_out_of_it() {
// The first row, flush with the list's top edge, give or take a fraction of a pixel of
// layout or scrolling.
assert_eq!(cut(&drawn_card(583., 583.)), None);
assert_eq!(cut(&drawn_card(582.7, 583.)), None);
assert_eq!(cut(&drawn_card(583.3, 583.)), None);
// A column of a fractional width: the bounds' intersection with the list differs from
// the card by a rounding error, which cut the first row's lifted card (#88).
let column = DrawnCard {
bounds: Bounds::new(point(px(533.3333), px(583.)), size(px(240.66666), px(357.))),
..drawn_card(583., 583.)
};
assert_ne!(column.visible.intersect(&column.bounds), column.bounds);
assert_eq!(cut(&column), None);
}
#[test]
fn a_card_the_list_shows_in_part_stays_cut_where_it_is() {
let half_scrolled = drawn_card(400., 583.);
assert_eq!(cut(&half_scrolled), Some(half_scrolled.visible));
let below = drawn_card(900., 583.);
assert_eq!(cut(&below), Some(below.visible));
}
+91
View File
@@ -0,0 +1,91 @@
//! The one order every section of cards follows: the chosen sort applied to the statistics' rows.
use arena_tracker_core::{ChampionRow, ChampionSort};
/// The positions of `rows` in display order. `rows` come A to Z (French collation), and every
/// sort is stable, so that order breaks every tie.
///
/// - `Name`: the rows' own order.
/// - `Mastery`: the champions with known points by points descending, then the ones whose points
/// are unknown (an unknown value is not a zero). When no row has a known value, the rows' own
/// order: the sort falls back to A to Z, and the player's preference stays as it is.
pub fn card_order(rows: &[ChampionRow], sort: ChampionSort) -> Vec<usize> {
let mut order: Vec<usize> = (0..rows.len()).collect();
if sort == ChampionSort::Mastery && rows.iter().any(|row| row.mastery_points.is_some()) {
// `None` sorts before every `Some`: reversed, the known values come first, highest first.
order.sort_by_key(|&ix| std::cmp::Reverse(rows[ix].mastery_points));
}
order
}
#[cfg(test)]
mod tests {
use arena_tracker_core::{Champion, ChampionRow, ChampionSort};
use super::card_order;
use crate::champion_table::tests::row;
/// Rows A to Z, as the statistics give them, each with its points.
fn rows(points: &[(&str, Option<u64>)]) -> Vec<ChampionRow> {
points
.iter()
.enumerate()
.map(|(id, (name, points))| ChampionRow {
champion: Champion {
id: id as u32 + 1,
..row(name).champion
},
mastery_points: *points,
..row(name)
})
.collect()
}
fn names(rows: &[ChampionRow], order: &[usize]) -> Vec<String> {
order
.iter()
.map(|&ix| rows[ix].champion.name.clone())
.collect()
}
#[test]
fn mastery_sorts_by_points_descending_then_by_name() {
let rows = rows(&[
("Ahri", Some(500)),
("Brand", Some(9_000)),
("Garen", Some(500)),
("Jinx", Some(0)),
("Zed", Some(500)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(
names(&rows, &order),
["Brand", "Ahri", "Garen", "Zed", "Jinx"]
);
}
#[test]
fn an_unknown_value_comes_after_the_known_ones_even_zero() {
let rows = rows(&[
("Ahri", None),
("Brand", Some(0)),
("Garen", None),
("Jinx", Some(12)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(names(&rows, &order), ["Jinx", "Brand", "Ahri", "Garen"]);
}
#[test]
fn without_any_known_value_the_cards_are_sorted_a_to_z() {
let rows = rows(&[("Ahri", None), ("Brand", None), ("Zed", None)]);
assert_eq!(card_order(&rows, ChampionSort::Mastery), [0, 1, 2]);
}
#[test]
fn the_name_sort_keeps_the_rows_order_whatever_the_points() {
let rows = rows(&[("Ahri", Some(1)), ("Brand", None), ("Zed", Some(900))]);
assert_eq!(card_order(&rows, ChampionSort::Name), [0, 1, 2]);
assert!(card_order(&[], ChampionSort::Mastery).is_empty());
}
}
+98 -2
View File
@@ -9,6 +9,7 @@ use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card_images::{self, CardImages};
use crate::text::{decimal, state_label};
struct Spec {
@@ -49,6 +50,12 @@ pub struct ChampionTable {
/// The clicked champion's id: it stays selected through sorting and reloads.
selected: Option<u32>,
scroll: UniformListScrollHandle,
/// The portraits of the rows painted, never GPUI's app-wide cache, which would keep every
/// one scrolled past (budget 4). Created at the first render.
images: Option<Entity<CardImages>>,
/// Guards the cache in tests.
#[cfg(test)]
pub(crate) renders: usize,
}
impl ChampionTable {
@@ -59,6 +66,22 @@ impl ChampionTable {
sort: None,
selected: None,
scroll: UniformListScrollHandle::new(),
images: None,
#[cfg(test)]
renders: 0,
}
}
/// The table is not shown any more: its portraits are given back, in memory and in the
/// window's atlas, and load again when it is drawn.
pub 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();
}
}
@@ -69,6 +92,11 @@ impl ChampionTable {
self.resort();
}
#[cfg(test)]
pub(crate) fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<String> {
self.rows.iter().map(|r| r.champion.name.clone()).collect()
@@ -227,7 +255,15 @@ fn cell_text(row: &ChampionRow, key: SortKey) -> String {
}
impl Render for ChampionTable {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
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 theme = cx.theme();
let (background, border, radius, muted) = (
theme.table,
@@ -256,7 +292,7 @@ impl Render for ChampionTable {
.track_scroll(&self.scroll)
.into_any_element()
};
div()
card_images::provide(div(), images)
.v_flex()
.relative()
.size_full()
@@ -297,6 +333,8 @@ pub(crate) mod tests {
name: name.into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
@@ -305,9 +343,67 @@ pub(crate) mod tests {
last_match_ms: None,
attempts: None,
state: None,
challenge: None,
mastery_points: None,
}
}
// Only the rows painted keep their portraits, and none is kept once the table is not shown.
#[gpui::test]
fn the_table_holds_only_the_portraits_of_the_rows_it_paints(cx: &mut gpui_kit::TestAppContext) {
use gpui_kit::{
AppContext as _, Bounds, VisualTestContext, WindowBounds, WindowOptions, point, px,
size,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
let dir = TestDir::new("table-portraits");
let rows: Vec<ChampionRow> = (1..=170)
.map(|id| {
let path = dir.path().join(format!("{id}.jpg"));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
let mut row = row(&format!("Champion {id:03}"));
row.champion.id = id;
row.portrait = Some(path);
row
})
.collect();
cx.update(gpui_kit::init);
let (window, table) = cx.update(|cx| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
})),
..Default::default()
};
gpui_kit::open_window(options, cx, |_, cx| {
cx.new(|_| {
let mut table = ChampionTable::new();
table.set_rows(rows, false);
table
})
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
let images = table.read_with(cx, |table, _| table.images().cloned().unwrap());
let held = images.read_with(cx, |images, _| images.loaded().len());
// The rows in the window's 860 px at 32 px each, not the 170.
assert!((10..=30).contains(&held), "{held} portraits held");
// Checked before the next frame: here the table is still the window, and draws again.
cx.update(|window, cx| {
table.update(cx, |table, cx| table.release_images(window, cx));
assert!(images.read(cx).held().is_empty());
});
}
#[test]
fn missing_values_show_a_dash() {
let row = row("Ahri");
+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}");
}
}
+285
View File
@@ -0,0 +1,285 @@
//! Launching Arena Tracker at the user's Windows logon (#67).
//!
//! Windows alone holds the choice, never `config.toml`: the logon starts the command of an
//! entry under `Run` unless the Task Manager's « Applications de démarrage » disabled it, which
//! it records under `StartupApproved\Run` without deleting the entry. Enabling the launch here
//! approves the entry again: the latest explicit choice wins.
use std::path::Path;
use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};
use windows::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_BINARY, REG_OPTION_NON_VOLATILE, REG_SZ,
REG_VALUE_TYPE, RRF_RT_REG_BINARY, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW,
RegDeleteKeyValueW, RegGetValueW, RegSetValueExW,
};
use windows::core::{HSTRING, Result, w};
use crate::release;
/// Given by the entry's command: the app starts hidden (`tray::start_hidden`).
pub const ARG: &str = "--logon";
/// The entry's value name in both keys.
const NAME: windows::core::PCWSTR = w!("ArenaTracker");
/// What the Task Manager writes for an enabled entry; an odd first byte disables it.
const APPROVED: [u8; 12] = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
/// Whether Windows started this process at logon.
pub fn launched_at_logon() -> bool {
std::env::args_os().nth(1).is_some_and(|arg| arg == ARG)
}
/// The two keys of the entry, under `HKEY_CURRENT_USER`.
struct Keys {
run: HSTRING,
approved: HSTRING,
}
impl Keys {
fn current_user() -> Keys {
Keys::under(r"Software\Microsoft\Windows\CurrentVersion")
}
/// `Run` and `Explorer\StartupApproved\Run` under `root`, as Windows lays them out.
fn under(root: &str) -> Keys {
Keys {
run: format!(r"{root}\Run").into(),
approved: format!(r"{root}\Explorer\StartupApproved\Run").into(),
}
}
/// Removes the entry and its approval, if they exist.
fn remove(&self) -> Result<()> {
for key in [&self.run, &self.approved] {
let deleted = unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, key, NAME) };
if deleted != ERROR_SUCCESS && deleted != ERROR_FILE_NOT_FOUND {
return Err(deleted.into());
}
}
Ok(())
}
}
/// The launch at the user's Windows logon.
pub struct LogonLaunch {
keys: Keys,
/// `None` outside an installed version: nothing to start that would outlive this build.
command: Option<String>,
}
impl LogonLaunch {
/// The entry of this Windows user, starting the installed executable.
pub fn installed() -> LogonLaunch {
LogonLaunch {
keys: Keys::current_user(),
command: std::env::current_exe()
.ok()
.and_then(|exe| installed_command(release::VERSION, &exe)),
}
}
/// Only an installed version offers the launch.
pub fn available(&self) -> bool {
self.command.is_some()
}
/// Whether the logon starts Arena Tracker: an entry the Task Manager did not
/// disable. Two registry reads, done when the settings are shown, never per frame.
pub fn enabled(&self) -> bool {
let found = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
&self.keys.run,
NAME,
RRF_RT_REG_SZ,
None,
None,
None,
)
};
if found != ERROR_SUCCESS {
return false;
}
let mut data = [0u8; 64];
let mut size = data.len() as u32;
let read = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
&self.keys.approved,
NAME,
RRF_RT_REG_BINARY,
None,
Some(data.as_mut_ptr().cast()),
Some(&mut size),
)
};
// No approval: the Task Manager never touched the entry. A value longer than any it
// writes is not one of its choices either.
read != ERROR_SUCCESS || approved(&data[..size as usize])
}
/// Writes or removes the entry. Enabling also approves it, undoing a Task Manager choice.
pub fn set(&self, enabled: bool) -> Result<()> {
if !enabled {
return self.keys.remove();
}
let Some(command) = &self.command else {
return Err(ERROR_FILE_NOT_FOUND.into());
};
let text: Vec<u8> = (command.encode_utf16().chain([0]))
.flat_map(u16::to_le_bytes)
.collect();
set_value(&self.keys.run, REG_SZ, &text)?;
set_value(&self.keys.approved, REG_BINARY, &APPROVED)
}
}
/// Removes this user's entry: an installation, or an uninstallation, starts without it.
pub fn forget() -> Result<()> {
Keys::current_user().remove()
}
/// The entry's command for an installed version: its executable in `current\`, a path that
/// Velopack keeps across updates. A development build has no version and runs elsewhere.
fn installed_command(version: Option<&str>, exe: &Path) -> Option<String> {
version?;
if exe.parent()?.file_name()? != "current" {
return None;
}
Some(format!("\"{}\" {ARG}", exe.to_str()?))
}
/// The Task Manager marks a disabled entry with an odd first byte (3, or 7 for some entries).
fn approved(value: &[u8]) -> bool {
value.first().is_none_or(|byte| byte & 1 == 0)
}
fn set_value(subkey: &HSTRING, kind: REG_VALUE_TYPE, data: &[u8]) -> Result<()> {
let mut key = HKEY::default();
unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
subkey,
None,
None,
REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE,
None,
&mut key,
None,
)
.ok()?;
let written = RegSetValueExW(key, NAME, None, kind, Some(data));
let _ = RegCloseKey(key);
written.ok()
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::path::Path;
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, RegDeleteTreeW};
use windows::core::HSTRING;
use super::{Keys, LogonLaunch, REG_BINARY, approved, installed_command, set_value};
/// A scratch copy of the two keys under the current user, removed when dropped.
pub(crate) struct Scratch {
root: HSTRING,
approved: HSTRING,
}
impl Scratch {
/// The launch of an installed version (`installed`) or of a development build, on
/// scratch keys named after the test.
pub(crate) fn launch(name: &str, installed: bool) -> (Scratch, LogonLaunch) {
let root = format!(
r"Software\nessar-arena-tracker-tests\{name}-{}",
std::process::id()
);
let keys = Keys::under(&root);
let scratch = Scratch {
root: root.as_str().into(),
approved: keys.approved.clone(),
};
scratch.drop_tree();
let command = installed.then_some(r#""C:\Arena\current\arena-tracker.exe" --logon"#);
let launch = LogonLaunch {
keys,
command: command.map(String::from),
};
(scratch, launch)
}
/// « Désactiver » in the Task Manager's « Applications de démarrage ».
pub(crate) fn disable_in_task_manager(&self) {
let disabled = [3, 0, 0, 0, 0xa0, 0x6e, 0x4b, 0x2c, 0x5e, 0x4d, 0xdb, 0x01];
set_value(&self.approved, REG_BINARY, &disabled).unwrap();
}
fn drop_tree(&self) {
let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &self.root) };
}
}
impl Drop for Scratch {
fn drop(&mut self) {
self.drop_tree();
}
}
#[test]
fn the_entry_follows_the_switch_and_the_task_manager_choice() {
let (scratch, launch) = Scratch::launch("follows", true);
assert!(!launch.enabled(), "a first installation starts disabled");
launch.set(true).unwrap();
assert!(launch.enabled());
scratch.disable_in_task_manager();
assert!(
!launch.enabled(),
"the settings show the Task Manager's choice"
);
launch.set(true).unwrap();
assert!(launch.enabled(), "enabling here approves the entry again");
launch.set(false).unwrap();
assert!(!launch.enabled());
// Nothing left behind, and removing what is gone is not an error.
launch.set(false).unwrap();
}
#[test]
fn a_build_outside_an_installation_cannot_enable_the_launch() {
let (_scratch, launch) = Scratch::launch("unavailable", false);
assert!(!launch.available());
assert!(launch.set(true).is_err());
assert!(!launch.enabled());
}
#[test]
fn only_an_installed_version_in_current_gets_a_command() {
let installed =
Path::new(r"C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe");
assert_eq!(
installed_command(Some("1.0.0"), installed).as_deref(),
Some(r#""C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe" --logon"#)
);
assert_eq!(installed_command(None, installed), None);
let built =
Path::new(r"C:\Users\A\AppData\Local\arena-tracker\target\release\arena-tracker.exe");
assert_eq!(installed_command(Some("1.0.0"), built), None);
}
#[test]
fn an_odd_first_byte_marks_a_disabled_entry() {
assert!(approved(&[2, 0, 0]));
assert!(approved(&[6, 0]));
assert!(approved(&[]));
assert!(!approved(&[3, 0, 0]));
assert!(!approved(&[7]));
}
}
+304 -107
View File
@@ -1,154 +1,313 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod assets;
mod banner_art;
mod card;
mod card_grid;
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;
mod page;
#[cfg(feature = "profile")]
mod profile;
mod release;
mod ring;
mod settings;
mod stats_page;
mod single_instance;
mod stage;
mod text;
mod theme;
mod title_bar;
mod tray;
mod worker;
use std::{rc::Rc, sync::Arc};
use std::{ops::ControlFlow, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, 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::base::async_util::unbounded;
use gpui_kit::component::*;
use gpui_kit::*;
use settings::{KeyEvent, KeyForm, KeyStore};
use stats_page::{PageEvent, StatsPage};
use worker::{Msg, spawn_follower};
use page::{ChampionSortChosen, Launch, LiveMatchStarted, MatchEndShown, Page};
use settings::{SettingsEvent, SettingsForm, SettingsStore, apply_theme};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use worker::{CatalogRefresh, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
enum Screen {
/// True first launch: the key form stands in for the page until a key is saved.
Prompt,
Page,
Settings,
}
struct RootView {
page: Entity<StatsPage>,
form: Entity<KeyForm>,
page: Entity<Page>,
form: Entity<SettingsForm>,
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
_subscriptions: Vec<Subscription>,
/// Started hidden at logon: the first frame, which GPUI draws as the window
/// opens, paints no page, so no portrait is decoded before the window is shown.
blank: bool,
_form_events: Subscription,
_champ_select: Subscription,
_recap: Subscription,
_live_match: Subscription,
_sort: Subscription,
}
impl RootView {
fn new(setup: Setup, window: &mut Window, cx: &mut Context<Self>) -> Self {
fn new(setup: Setup, hidden: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
let Setup {
tracker,
game_data,
riot_id,
notice,
store,
} = setup;
// 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 preferences = store.preferences();
let (tx, rx) = unbounded();
let catalog_refresh = game_data.map(|data| CatalogRefresh::start(data, tx.clone()));
let page = cx.new(|cx| {
StatsPage::new(
Page::new(
tracker.clone(),
notice,
!first_launch,
Launch {
notice,
champion_sort: preferences.champion_sort,
open_recap_at_match_end: preferences.open_recap_at_match_end,
},
rx,
tx.clone(),
window,
cx,
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let subscriptions = vec![
cx.subscribe_in(
&page,
window,
|this, _, event: &PageEvent, window, cx| match event {
PageEvent::OpenSettings => {
this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Settings;
cx.notify();
}
},
),
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, _, cx| {
let form = cx.new(|cx| SettingsForm::new(store, tracker.clone(), window, cx));
let form_events = cx.subscribe_in(
&form,
window,
|this, _, event: &SettingsEvent, window, cx| {
match event {
KeyEvent::Saved if this.screen == Screen::Prompt => {
// 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());
this.page.update(cx, |page, cx| page.following(cx));
SettingsEvent::Back => {}
// « Paramètres » stays open.
SettingsEvent::AccountDeleted(puuid) => {
return this
.page
.update(cx, |page, cx| page.account_deleted(puuid, window, cx));
}
// Only the title bar changes.
SettingsEvent::UpdateReady => return cx.notify(),
SettingsEvent::Preferences(preferences) => {
let open = preferences.open_recap_at_match_end;
return this
.page
.update(cx, |page, _| page.set_open_recap_at_match_end(open));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)),
KeyEvent::Back => {}
}
this.screen = Screen::Page;
this.show_page(window, cx);
},
);
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, transition: &page::ChampSelectTransition, window, cx| {
// Only on entry: the window stays open after the champ select.
if transition.entered
&& 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, true))
.detach();
}
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
this.show_page(window, cx);
}
},
);
// The end of a game showed its recap or the Challenge: as for a champ select, « Paramètres »
// gives way and the window comes above the others, League keeping the keyboard.
let recap = cx.subscribe_in(&page, window, |this, _, _: &MatchEndShown, window, cx| {
if let Some(hwnd) = tray::window_hwnd(window) {
cx.spawn(async move |_, _| tray::reveal(hwnd, true))
.detach();
}
if this.screen == Screen::Settings {
this.show_page(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,
|this, _, ChampionSortChosen(sort): &ChampionSortChosen, cx| {
this.form
.update(cx, |form, cx| form.save_champion_sort(*sort, cx));
},
);
spawn_follower(tracker, riot_id, catalog_refresh, tx);
if hidden {
// Runs once GPUI's first frame is drawn. A hidden or minimized window gets no
// other frame: the page is painted when the window is shown.
cx.defer_in(window, |this, _, cx| {
this.blank = false;
cx.notify();
}),
];
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
Screen::Page
};
});
}
RootView {
page,
form,
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_subscriptions: subscriptions,
focus: initial_focus(window, cx),
screen: Screen::Page,
blank: hidden,
_form_events: form_events,
_champ_select: champ_select,
_recap: recap,
_live_match: live_match,
_sort: sort,
}
}
fn can_refresh(&self, cx: &App) -> bool {
!self.page.read(cx).busy()
}
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
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();
form.read_accounts();
});
self.page.update(cx, |page, cx| page.hidden(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
/// Leaves « Paramètres » for the page.
fn show_page(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.form.update(cx, |form, cx| form.reset(cx));
self.screen = Screen::Page;
self.page.update(cx, |page, cx| page.uncovered(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
impl Render for RootView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh =
refresh_button(self.can_refresh(cx), cx).on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.request_refresh(cx));
}
}));
let on_page = self.screen == Screen::Page;
let settings = settings_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)));
// The settings show the ready version next to « Redémarrer ».
let update = self.form.read(cx).update_ready().then(|| {
update_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)))
});
let content = match self.screen {
_ if self.blank => div().into_any_element(),
Screen::Page => self.page.clone().into_any_element(),
Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(),
Screen::Settings => self.form.clone().into_any_element(),
};
div().size_full().child(content)
div()
.id("arena-tracker")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(refresh, settings, update, window, cx))
.child(div().flex_1().min_h_0().child(content))
}
}
/// Shown instead of the app when the configuration or the database cannot be loaded.
struct Unavailable(Vec<String>);
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
}
impl Render for Unavailable {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.items_center()
.justify_center()
.children(self.0.clone())
.child(title_bar(
refresh_button(false, cx),
settings_button(false, cx),
None,
window,
cx,
))
.child(
div()
.v_flex()
.flex_1()
.items_center()
.justify_center()
.children(self.lines.clone()),
)
}
}
fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
// Tab dispatch needs a focused element inside gpui-kit's root key context.
let focus = cx.focus_handle();
focus.focus(window, cx);
focus
}
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,
store: SettingsStore,
}
/// Loads the configuration and opens the database, or gives the lines to show instead. A
/// missing config file is fine: the app then asks for the key.
fn startup() -> Result<Setup, Vec<String>> {
/// missing config file is fine: the defaults apply.
fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
let bad_config = |error: String| {
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
]
(
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
],
Preferences::default(),
)
};
let dir =
data_dir().ok_or_else(|| bad_config("la variable APPDATA n'est pas définie.".into()))?;
@@ -162,65 +321,103 @@ fn startup() -> Result<Setup, Vec<String>> {
Some(format!("Table des Saisons invalide : {e}")),
),
};
let api = Arc::new(RiotApi::new(config.riot_api_key.clone(), &config.region));
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api.clone()))
.map_err(|e| vec![e.to_string()])?
let api = RiotApi::new(config.relay_url(), &config.region);
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api))
.map_err(|e| (vec![e.to_string()], config.preferences))?
.with_seasons(seasons)
.with_champions(Box::new(DataDragon::new()), dir.join("portraits"))
.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),
store: SettingsStore::new(path, config),
})
}
fn follow_system_appearance(window: &mut Window, cx: &mut App) {
let sync = |window: &mut Window, cx: &mut App| {
let mode = ThemeMode::from(window.appearance());
if cx.theme().mode != mode {
Theme::sync_system_appearance(Some(window), cx);
debug_assert_eq!(cx.theme().mode, mode);
fn main() {
release::handle_command();
// 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;
}
};
sync(window, cx);
window.observe_window_appearance(sync).detach();
}
fn main() {
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
// Started by the logon entry: hidden, or minimized (#67).
let at_logon = logon::launched_at_logon();
// Only the single instance gets here: a launch relayed to a running one installs nothing.
let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else {
return;
};
let app = gpui_kit::application().with_assets(assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
// The default dark table header text has low contrast against its background.
let dark = Rc::make_mut(&mut Theme::global_mut(cx).dark_theme);
dark.colors.table_head_foreground = dark.colors.muted_foreground.clone();
journal::flush_on_quit(cx);
card_grid::init(cx);
page::init(cx);
theme::init(cx);
#[cfg(feature = "profile")]
profile::start(cx);
let bounds = Bounds::centered(None, size(px(1280.), px(860.)), cx);
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..Default::default()
..TitleBar::title_bar_options()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(MIN_WINDOW_SIZE),
show: !at_logon,
focus: !at_logon,
..Default::default()
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err(lines) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
cx.new(|_| Unavailable(lines))
Ok(mut setup) => {
setup.notice = (update_notice.into_iter().chain(setup.notice))
.reduce(|update, seasons| format!("{update}\n{seasons}"));
gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
motion::follow_windows_setting(window, cx);
minimized::skip_paint_while_minimized(window);
// The settings form installs the tray that hides the window.
let root = cx.new(|cx| RootView::new(setup, at_logon, window, cx));
if at_logon {
tray::start_hidden(window, bounds);
}
root
})
.map(drop)
}
Err((mut lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
lines.extend(update_notice);
single_instance::accept_relaunches(window);
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
apply_theme(preferences.theme, window, cx);
})
.detach();
// Without a readable configuration the one-time notice could not be recorded.
tray::Tray::install_saved(window, preferences.close_to_tray, None, cx);
if at_logon {
tray::start_hidden(window, bounds);
}
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
})
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
#[cfg(test)]
mod tests;
+44
View File
@@ -0,0 +1,44 @@
//! A minimised window draws nothing, yet GPUI's vsync thread invalidates it at each vsync, and
//! each WM_PAINT went through GPUI, which has no frame to draw while minimised, then
//! DefWindowProc: the UI thread spent more minimised than visible (budget 3,
//! `docs/performance.md`). The paint is validated here instead, before GPUI sees it.
use gpui_kit::Window;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Gdi::ValidateRect;
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{IsIconic, WM_NCDESTROY, WM_PAINT};
use crate::tray::window_hwnd;
/// Subclass ids are per procedure.
const MINIMIZED_SUBCLASS: usize = 0;
pub(crate) fn skip_paint_while_minimized(window: &Window) {
if let Some(hwnd) = window_hwnd(window) {
// Without the subclass, GPUI handles these paints as before.
let _ = unsafe { SetWindowSubclass(hwnd, Some(paint_proc), MINIMIZED_SUBCLASS, 0) };
}
}
unsafe extern "system" fn paint_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
_id: usize,
_data: usize,
) -> LRESULT {
match message {
// GPUI gives its frame callback back at the restore's WM_SIZE, and draws then.
WM_PAINT if unsafe { IsIconic(hwnd) }.as_bool() => {
let _ = unsafe { ValidateRect(Some(hwnd), None) };
return LRESULT(0);
}
WM_NCDESTROY => {
let _ = unsafe { RemoveWindowSubclass(hwnd, Some(paint_proc), MINIMIZED_SUBCLASS) };
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
+334
View File
@@ -0,0 +1,334 @@
//! What decides whether the app animates, and when (#86): the Windows setting followed into
//! `App::reduce_motion`, the animations waiting for « Défi » to be visible, and the veil of the
//! switch between tabs. The page says when « Défi » is visible.
use std::time::{Duration, Instant};
use gpui_kit::base::apply_system_reduce_motion;
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::{App, Global, Window};
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{
SPI_SETCLIENTAREAANIMATION, WM_NCDESTROY, WM_SETTINGCHANGE,
};
use crate::tray::window_hwnd;
/// How long the screen leaving takes to go under the veil.
const FADE_OUT: Duration = Duration::from_millis(130);
/// How long the screen arriving takes to come out of it.
const FADE_IN: Duration = Duration::from_millis(280);
pub(crate) use arena_tracker_core::MatchEnd;
/// The comet's flight to the nearest tick, just after noon.
const COMET_SHORTEST: f32 = 0.65;
/// What the flight takes longer per turn of the ring, up to the last tick.
const COMET_PER_TURN: f32 = 0.55;
/// How long the tick, the card and the splash take to settle once the comet lands, or from the
/// start without a comet, in seconds.
pub(crate) const MATCH_SETTLE: f32 = 1.2;
/// How long the counter's roll and the fade in of the « Dernière Partie » line take, in seconds.
pub(crate) const COUNTER_ROLL: f32 = 0.7;
/// The end of a followed Match being played: what it brought, on which tick, from when. Fixed
/// when it starts; the ring, the banner and the card read their frame from it.
#[derive(Clone, Copy)]
pub(crate) struct MatchAnimation {
pub start: Instant,
pub end: MatchEnd,
pub champion_id: u32,
/// The champion's tick, among `count`.
pub index: usize,
pub count: usize,
pub state: arena_tracker_core::ChampionState,
}
impl MatchAnimation {
/// A champion Completed sends the comet first; anything else settles from the start.
pub fn has_comet(self) -> bool {
self.end == MatchEnd::Completed
}
/// How long the comet flies: in proportion to how far round the ring the tick is.
pub fn flight(self) -> f32 {
if self.has_comet() {
COMET_SHORTEST + COMET_PER_TURN * self.index as f32 / self.count as f32
} else {
0.
}
}
pub fn elapsed(self, now: Instant) -> f32 {
now.saturating_duration_since(self.start).as_secs_f32()
}
/// Seconds since the comet landed (since the start without one): negative while it flies.
pub fn since_landing(self, now: Instant) -> f32 {
self.elapsed(now) - self.flight()
}
pub fn finished(self, now: Instant) -> bool {
self.since_landing(now) >= MATCH_SETTLE
}
}
/// Animations asked for while « Défi » is not in front of the player: only the strongest is
/// kept, and it plays once « Défi » shows again.
pub(crate) struct Deferred<A> {
waiting: Option<A>,
}
impl<A> Default for Deferred<A> {
fn default() -> Self {
Deferred { waiting: None }
}
}
impl<A: Ord> Deferred<A> {
/// The animation waiting, if any.
pub fn waiting(&self) -> Option<&A> {
self.waiting.as_ref()
}
/// Gives back the animation to play now when « Défi » is visible, else keeps it if it is the
/// strongest waiting.
pub fn request(&mut self, animation: A, visible: bool) -> Option<A> {
if visible {
return Some(animation);
}
if self
.waiting
.as_ref()
.is_none_or(|waiting| animation > *waiting)
{
self.waiting = Some(animation);
}
None
}
/// « Défi » shows again: the animation waiting, if any, to play now.
pub fn shown(&mut self) -> Option<A> {
self.waiting.take()
}
}
/// The screen leaving « Défi » or « Statistiques » goes under a veil of the page's background,
/// then the one arriving comes out of it. A veil rather than the content's own opacity or
/// position: either is part of a cached view's key, so fading or sliding the content would draw
/// the grid, the ring and the charts again at each frame and build the cards again (rule #1).
pub(crate) struct Fade {
phase: FadePhase,
/// The veil's opacity when the phase started: a switch during a transition starts again from
/// where the veil is.
from: f32,
start: Instant,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum FadePhase {
/// The screen leaving goes under the veil.
Out,
/// The screen arriving comes out of it.
In,
}
impl Fade {
pub fn covering(from: f32, start: Instant) -> Self {
Fade {
phase: FadePhase::Out,
from,
start,
}
}
pub fn uncovering(from: f32, start: Instant) -> Self {
Fade {
phase: FadePhase::In,
from,
start,
}
}
pub fn phase(&self) -> FadePhase {
self.phase
}
/// The veil's opacity, 0 to 1.
pub fn veil(&self, now: Instant) -> f32 {
let progress = self.progress(now);
match self.phase {
FadePhase::Out => self.from + (1. - self.from) * ease_in(progress),
FadePhase::In => self.from * (1. - ease_out(progress)),
}
}
pub fn finished(&self, now: Instant) -> bool {
self.progress(now) >= 1.
}
fn duration(&self) -> Duration {
match self.phase {
FadePhase::Out => FADE_OUT,
FadePhase::In => FADE_IN,
}
}
fn progress(&self, now: Instant) -> f32 {
let elapsed = now.saturating_duration_since(self.start);
(elapsed.as_secs_f32() / self.duration().as_secs_f32()).min(1.)
}
}
/// Close to CSS's `ease-in`.
pub(crate) fn ease_in(t: f32) -> f32 {
t * t
}
/// Close to the reference's `cubic-bezier(.2, .8, .2, 1)`.
pub(crate) fn ease_out(t: f32) -> f32 {
1. - (1. - t).powi(3)
}
/// Follows the Windows « Show animations » setting while the app runs. gpui-base reads it into
/// `App::reduce_motion` at start (`gpui_kit::init`) but not on its change, which Windows
/// broadcasts to every top-level window: the window's own messages are watched for it, with no
/// polling.
pub(crate) fn follow_windows_setting(window: &Window, cx: &mut App) {
let Some(hwnd) = window_hwnd(window) else {
return;
};
let (tx, rx) = unbounded::<()>();
let data = Box::into_raw(Box::new(tx));
// The subclass owns the sender until WM_NCDESTROY. This window belongs to the UI thread.
if !unsafe { SetWindowSubclass(hwnd, Some(setting_proc), SETTING_SUBCLASS, data as usize) }
.as_bool()
{
drop(unsafe { Box::from_raw(data) });
return;
}
cx.spawn(async move |cx| {
while rx.recv().await.is_ok() {
cx.update(|cx| {
apply_system_reduce_motion(cx);
cx.set_global(AnimationSetting);
});
}
})
.detach();
}
/// Set again each time the Windows setting is read again, for the page to observe: turned off,
/// nothing animates any more and nothing waits.
#[derive(Default)]
pub(crate) struct AnimationSetting;
impl Global for AnimationSetting {}
/// The tray's subclass is 0.
const SETTING_SUBCLASS: usize = 1;
unsafe extern "system" fn setting_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
_id: usize,
data: usize,
) -> LRESULT {
let sender = data as *mut Sender<()>;
if animation_setting_changed(message, wparam.0) {
// Applied outside the window procedure, by the task above.
let _ = unsafe { &*sender }.try_send(());
} else if message == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(setting_proc), SETTING_SUBCLASS);
drop(Box::from_raw(sender));
}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
/// Whether a window message says the Windows « Show animations » setting changed.
fn animation_setting_changed(message: u32, wparam: usize) -> bool {
message == WM_SETTINGCHANGE && wparam == SPI_SETCLIENTAREAANIMATION.0 as usize
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use windows::Win32::UI::WindowsAndMessaging::{
SPI_SETCLIENTAREAANIMATION, SPI_SETMOUSESPEED, WM_SETTINGCHANGE, WM_SIZE,
};
use super::{Deferred, Fade, animation_setting_changed};
#[test]
fn an_animation_asked_for_while_visible_plays_at_once() {
let mut deferred = Deferred::default();
assert_eq!(deferred.request(1, true), Some(1));
}
#[test]
fn of_the_animations_asked_for_while_hidden_only_the_strongest_plays_once_shown() {
let mut deferred = Deferred::default();
assert_eq!(deferred.request(1, false), None);
assert_eq!(deferred.request(3, false), None);
assert_eq!(deferred.request(2, false), None);
assert_eq!(deferred.shown(), Some(3));
// It plays once.
assert_eq!(deferred.shown(), None);
}
fn at(start: Instant, ms: u64) -> Instant {
start + Duration::from_millis(ms)
}
#[test]
fn the_veil_covers_the_screen_leaving_in_130_ms_and_uncovers_the_one_arriving_in_280_ms() {
let start = Instant::now();
let out = Fade::covering(0., start);
assert_eq!(out.veil(start), 0.);
assert!(!out.finished(at(start, 129)));
assert!(out.finished(at(start, 130)));
assert_eq!(out.veil(at(start, 130)), 1.);
// Slow at first, as the reference's ease-in.
assert!(out.veil(at(start, 65)) < 0.5);
let arrival = Fade::uncovering(1., start);
assert_eq!(arrival.veil(start), 1.);
assert!(!arrival.finished(at(start, 279)));
assert!(arrival.finished(at(start, 280)));
assert_eq!(arrival.veil(at(start, 280)), 0.);
// Fast at first, then settling.
assert!(arrival.veil(at(start, 140)) < 0.5);
}
#[test]
fn a_switch_during_a_transition_starts_from_where_the_veil_is() {
let start = Instant::now();
assert_eq!(Fade::covering(0.4, start).veil(start), 0.4);
assert_eq!(Fade::uncovering(0.4, start).veil(start), 0.4);
assert_eq!(Fade::uncovering(0.4, start).veil(at(start, 280)), 0.);
}
#[test]
fn only_a_change_of_the_animations_setting_is_read_again() {
assert!(animation_setting_changed(
WM_SETTINGCHANGE,
SPI_SETCLIENTAREAANIMATION.0 as usize
));
// The theme (no parameter) or another setting.
assert!(!animation_setting_changed(WM_SETTINGCHANGE, 0));
assert!(!animation_setting_changed(
WM_SETTINGCHANGE,
SPI_SETMOUSESPEED.0 as usize
));
assert!(!animation_setting_changed(
WM_SIZE,
SPI_SETCLIENTAREAANIMATION.0 as usize
));
}
}
+384
View File
@@ -0,0 +1,384 @@
//! 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, 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, LiveMatch, Scope, SeasonScope, StateFilter,
Statistics, Status, SyncProgress, Tracker,
};
use gpui_kit::base::async_util::Sender;
use gpui_kit::component::input::InputState;
use gpui_kit::component::select::{SearchableVec, SelectGroup, SelectItem, SelectState};
use gpui_kit::*;
use profiling::shown;
use scrollbar::PageScrollbar;
use statistics::ChartsRow;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
mod cards;
mod champ_select;
mod display;
mod displayed;
mod friends;
mod home;
mod hover;
mod import_view;
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)]
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.;
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
/// The sorts on offer, in the selector's order.
const SORTS: [(ChampionSort, &str); 2] = [
(ChampionSort::Mastery, "Maîtrise"),
(ChampionSort::Name, "A–Z"),
];
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// 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;
fn title(&self) -> SharedString {
self.title.clone()
}
fn value(&self) -> &String {
&self.puuid
}
}
/// What the page starts from.
pub struct Launch {
pub notice: Option<String>,
/// 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.
pub struct ChampSelectTransition {
pub entered: bool,
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The end of a game was decided: « Parties » opened its recap, or « Défi » shows. As for a champ
/// select, « Paramètres » gives way and the window comes above the others (#129).
pub struct MatchEndShown;
impl EventEmitter<MatchEndShown> 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 {}
/// 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
/// strongest. The order of the fields is that ranking (derived `Ord`).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct WaitingMatch {
end: MatchEnd,
started_at_ms: i64,
champion_id: u32,
}
/// 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 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.
animation: Option<MatchAnimation>,
/// The banner before the Match: its text until the comet lands, its splash under the comet.
previous_banner: Option<home::BannerContent>,
/// The champion's card before the Match, drawn until its change lands.
previous_card: Option<Rc<Card>>,
/// The champion whose card the grid showed: it stays shown until the animation ends, even
/// if the filter now leaves it out, so that it changes in place.
kept_card: Option<u32>,
}
impl MatchPlayback {
fn active(&self) -> bool {
self.waiting.waiting().is_some() || self.animation.is_some()
}
}
/// The home grid of new statistics that arrived while the pointer held it still, prepared on
/// their arrival: the pointer leaving only puts it in place (rule #1).
struct NextHome {
order: Vec<usize>,
cards: Rc<[Card]>,
shown: Vec<usize>,
count: SharedString,
}
pub struct Page {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
champ_select: LiveChampSelect,
/// 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.
pinned: Option<String>,
/// The Account of the last requested statistics.
shown: Option<String>,
progress: Option<SyncProgress>,
import_view: import_view::ImportView,
refresh: RefreshGate,
stats_job: RefreshGate,
stats_generation: u64,
/// Until the follower's first round ends.
pending_round: bool,
crashed: bool,
last_reload: Instant,
current_season: Option<String>,
/// The tab the navigation shows as chosen. Not persisted: the app opens on the Challenge.
/// The screen drawn (`shown_tab`) follows it once the screen leaving is under the veil.
tab: Tab,
/// The tab whose screen is drawn.
shown_tab: Tab,
/// The transition between the tabs, while it runs.
fade: Option<Fade>,
/// A frame of the transition is asked for.
frame_asked: bool,
/// The cards lifted over their grid, by grid: the one under the pointer or the keyboard, and
/// those settling back (#88).
lifts: Lifts<EntityId>,
/// The grid whose card the keyboard lifted: the pointer moving puts it down.
lifted_by_keyboard: Option<WeakEntity<CardGrid>>,
/// « Paramètres » stands in for the page.
covered: bool,
/// The end of a followed Match, from its round to the end of its animation.
playback: MatchPlayback,
/// The pointer was on the home grid when a followed Match changed it: its cards change in
/// place, and the order, the filter and the count wait for the pointer to leave so that
/// nothing moves under it.
hold_grid: bool,
/// While `hold_grid`, the grid it waits to show, once the statistics are there.
next_home: Option<NextHome>,
/// The champ select's entry (#87), from when the window shows it until its hand is dealt.
entry: Option<Entry>,
/// A champ select started while the window or the page was not in front: its entry plays
/// once they are.
entry_waiting: bool,
/// The hand leaving at the end of a champ select. The end itself is applied once the veil
/// of the tabs covers the screen (`finish_exit`), so the champ select stays drawn until then.
leave: Option<Leave>,
/// The cards of the hand an ally just took, going down to their place.
taken: Vec<Taken>,
/// The card of the hand under the pointer or the keyboard while it is still dealt: it is
/// lifted once in its place.
hover_waiting: Option<CardHovered>,
/// A frame of the champ select's motion is asked for.
stage_frame_asked: bool,
/// The animations played, in order.
#[cfg(test)]
played: Vec<MatchEnd>,
/// The Season of the Statistics tab.
season: SeasonScope,
format: Option<Format>,
filter: StateFilter,
/// Kept and reapplied whenever the table's rows are rebuilt.
search: ChampionSearch,
search_input: Entity<InputState>,
stats: Option<Statistics>,
stats_error: Option<String>,
/// The Season whose Challenge the home shows: the one chosen on the Statistics tab, else the
/// current one. None when there is no such Season.
home_season: Option<SharedString>,
/// The home's scope when it differs from the Statistics tab's, else the home reads `stats`.
home_scope: Option<Scope>,
/// Only for a `home_scope`.
home_stats: Option<Statistics>,
home_error: Option<String>,
/// 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 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.
home_filter: StateFilter,
home_search: ChampionSearch,
home_search_input: Entity<InputState>,
/// The sort the player chose, saved with the preferences; `None` until one is chosen, which
/// sorts by Mastery Points.
champion_sort: Option<ChampionSort>,
sort_select: Entity<SelectState<Vec<SharedString>>>,
/// The positions of the home statistics' rows in the cards' order, which every section
/// follows. Computed again only when those statistics or the sort change (`reorder`).
order: Vec<usize>,
/// How many times `order` was computed.
#[cfg(test)]
reorders: usize,
stored: Option<usize>,
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>,
charts: Entity<ChartsRow>,
table: Entity<ChampionTable>,
/// The home's champions, one card each.
home_grid: Entity<CardGrid>,
/// The home's cards were not rebuilt for the latest statistics, as the home was not shown.
home_cards_stale: bool,
/// How many cards the grid shows, prepared when the filter or search change.
home_shown_count: SharedString,
/// The Anvil champions of the champ select, one card each in the home grid's order, with
/// the reasons the champ select gives. Only drawn during a champ select.
anvil_grid: Entity<CardGrid>,
/// How many Anvil champions the row shows, prepared with the cards.
anvil_count: SharedString,
/// « Autres champions »: folded at each new champ select. While it is, it holds no card.
others_open: bool,
/// Filters this section only; emptied with each new champ select.
others_search: ChampionSearch,
others_search_input: Entity<InputState>,
/// The champions without an Anvil (all of them when the list is unknown), only built while
/// the section is open: a virtualized grid, which the champ select's scrolling moves.
others_grid: Entity<CardGrid>,
/// The scrolling of the whole champ select (the banner, the Anvil champions and the section),
/// and where the section's grid starts in it, which says the rows of the grid in view.
paging: Paging,
/// Its scrollbar, a view of its own for the fade.
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<()>,
}
+163
View File
@@ -0,0 +1,163 @@
use super::{ChampionSortChosen, Page, Tab};
use crate::card::Card;
use crate::card_order::card_order;
use arena_tracker_core::{ChampionRow, ChampionSearch, ChampionSort, StateFilter};
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// 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();
}
/// The cards' order for the home statistics and the sort.
pub(in crate::page) fn sorted_order(&mut self) -> Vec<usize> {
#[cfg(test)]
{
self.reorders += 1;
}
let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery);
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
card_order(rows, sort)
}
/// The pointer left the home grid it held still: the grid prepared when the statistics
/// arrived takes its place, built and sorted already.
pub(in crate::page) fn release_home(&mut self, cx: &mut Context<Self>) {
let held = std::mem::take(&mut self.hold_grid);
let Some(next) = self.next_home.take().filter(|_| held) else {
return;
};
self.order = next.order;
self.home_shown_count = next.count;
self.home_grid.update(cx, |grid, cx| {
grid.set_cards(next.cards, cx);
grid.set_shown(next.shown, cx);
});
}
/// The player changed the home's filter or search: the grid follows at once, even under the
/// pointer or with a card kept for its Match.
pub(in crate::page) fn home_filtered(&mut self, cx: &mut Context<Self>) {
self.release_home(cx);
self.playback.kept_card = None;
self.refresh_home(cx);
}
/// The home grid no longer waits for the pointer to leave: what comes next rebuilds it.
pub(in crate::page) fn stop_holding(&mut self) {
self.hold_grid = false;
self.next_home = None;
}
/// The home statistics' rows in the cards' order: the single iteration the home grid and
/// « Autres champions » follow (the Anvil champions are always A to Z).
pub(in crate::page) fn ordered_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
self.order.iter().filter_map(move |&ix| rows.get(ix))
}
/// The player chose a sort: the cards of every section follow it, and it is saved.
pub(crate) fn choose_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
if self.champion_sort == Some(sort) {
return;
}
self.stop_holding();
self.champion_sort = Some(sort);
self.reorder();
if self.in_champ_select() {
self.prepare_champ_select(cx);
}
self.prepare_home_cards(cx);
self.refresh_home(cx);
cx.emit(ChampionSortChosen(sort));
cx.notify();
}
/// One card per champion, in the cards' order, for when the statistics or the sort change.
/// While the home is not shown the next switch to it does (`home_cards_stale`).
pub(in crate::page) fn prepare_home_cards(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Challenge {
self.home_cards_stale = true;
return;
}
self.home_cards_stale = false;
let cards: Rc<[Card]> = self.ordered_rows().map(Card::from_row).collect();
self.home_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
}
/// At the end of a champ select the home is as at launch: « Tous » and an empty search. The
/// Account and Season viewed were never touched.
pub(in crate::page) fn reset_home_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.home_filter = StateFilter::All;
self.home_search = ChampionSearch::new("");
self.home_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
/// Rebuilds the Statistics tab's rows; while it is not shown, the next switch does.
pub(in crate::page) fn refresh_table(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Statistics {
return;
}
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
});
}
/// 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 {
return;
}
if self.hold_grid {
// Nothing moves under the pointer: the grid it leaves for follows instead.
let shown = (self.next_home.as_ref()).map(|next| self.home_shown(&next.order));
if let (Some(next), Some(shown)) = (self.next_home.as_mut(), shown) {
next.count = shown.len().to_string().into();
next.shown = shown;
}
return;
}
let shown = self.home_shown(&self.order);
self.home_shown_count = shown.len().to_string().into();
self.home_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// The cards the home's filter and search keep, as indices of its cards in `order`. The
/// card of a followed Match's champion that was shown stays until its animation ends, so
/// that it changes in place (#89).
pub(in crate::page) fn home_shown(&self, order: &[usize]) -> Vec<usize> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let changing = self.playback.kept_card;
// The cards are the rows in the cards' order: a card's index is its position.
order
.iter()
.filter_map(|&ix| rows.get(ix))
.enumerate()
.filter(|(_, row)| {
Some(row.champion.id) == changing
|| (self.home_filter.keeps(row) && self.home_search.matches(&row.champion))
})
.map(|(ix, _)| ix)
.collect()
}
}
+124
View File
@@ -0,0 +1,124 @@
use super::{ChampSelectTransition, Page, Tab};
use crate::worker::LiveChampSelect;
use arena_tracker_core::{account_riot_id, same_riot_id};
use gpui_kit::*;
pub(in crate::page) const UNKNOWN_ANVIL: &str =
"Champions de l'Enclume non communiqués par le client";
mod cards;
mod motion;
mod render;
impl Page {
/// 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.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
/// one with new picks and bans.
pub(in crate::page) fn change_champ_select(
&mut self,
champ_select: LiveChampSelect,
window: &mut Window,
cx: &mut Context<Self>,
) {
let previous = self.champ_select.as_ref();
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() {
// 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);
// Its entry plays once the window shows it (#63 reveals it without focus).
self.entry_waiting = true;
} else {
self.forget_stage();
self.reset_home_view(window, cx);
self.anvil_grid
.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 {
// 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.)));
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 {
entered: self.in_champ_select(),
});
}
// The hand as it was, to see which card an ally just took.
let before = (!switch).then(|| self.anvil_grid.read(cx).cards().clone());
// Any change (a hover or a lock-in too) changes the reasons of the cards. Only
// the client's events get here: no polling.
self.prepare_champ_select(cx);
if let Some(before) = before {
self.lower_taken(&before, window, cx);
}
self.start_entry(window, cx);
}
}
+175
View File
@@ -0,0 +1,175 @@
use crate::card::Card;
use crate::card_grid::{CardGrid, RevealRow};
use crate::page::{Page, home};
use arena_tracker_core::{ChampSelect, ChampionRow, ChampionSearch};
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// A new grid for « Autres champions », whose hover lights the ring as the others do. The
/// one it replaces puts out the tick it lit.
fn new_others_grid(&mut self, cx: &mut Context<Self>) {
let replaced = self.others_grid.entity_id();
// The new grid is not laid out: the old one's place is not its own.
self.paging.top.set(None);
let paging = self.paging.clone();
self.others_grid = cx.new(|_| CardGrid::paged(paging));
self.others_hover = Self::light_and_reveal(&self.others_grid, cx);
self.lifts.drop_grid(replaced);
self.light(replaced, None, cx);
}
/// What `light_on_hover` does for the grid of « Autres champions », and scrolls the champ
/// select to the row the keyboard reaches: the grid holds no scrolling of its own.
pub(in crate::page) fn light_and_reveal(
grid: &Entity<CardGrid>,
cx: &mut Context<Self>,
) -> [Subscription; 3] {
let [hovered, put_down] = Self::light_on_hover(grid, cx);
let reveal = cx.subscribe(grid, |this, _, row: &RevealRow, cx| this.reveal(*row, cx));
[hovered, put_down, reveal]
}
/// Scrolls the champ select the least that shows the row of « Autres champions » the
/// keyboard reached.
fn reveal(&mut self, row: RevealRow, cx: &mut Context<Self>) {
let Some(grid_top) = self.paging.top.get() else {
return;
};
let scroll = &self.paging.scroll;
let (top, bottom) = (grid_top + row.top, grid_top + row.bottom);
let (scrolled, viewport) = (-scroll.offset().y, scroll.bounds().size.height);
let to = if top < scrolled {
top
} else if bottom > scrolled + viewport {
bottom - viewport
} else {
return;
};
scroll.set_offset(point(scroll.offset().x, -to));
cx.notify();
}
pub(in crate::page) fn in_champ_select(&self) -> bool {
self.champ_select.is_some()
}
pub(in crate::page) fn live_champ_select(&self) -> Option<&ChampSelect> {
self.champ_select.as_ref().map(|(_, pick)| pick)
}
/// The cards of the Anvil champions row (`stats_notice` says why there are none when the
/// statistics are missing). For when the champ select, the statistics or the status change.
pub(in crate::page) fn prepare_champ_select(&mut self, cx: &mut Context<Self>) {
// The statistics' own order, A to Z, whatever sort the player chose: it is the client's
// order of the Anvil champions. An id the rows do not know is skipped.
let champ_select = self.live_champ_select();
let anvil = champ_select.and_then(|pick| pick.anvil_champions.as_deref());
let ids = anvil.unwrap_or_default();
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let cards =
self.champ_select_cards(rows.iter().filter(|row| ids.contains(&row.champion.id)));
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.champ_select_banner = home::BannerContent::champ_select(
self.home_season.as_ref(),
self.home_statistics(),
anvil.is_some(),
remaining_pickable.count(),
splash,
);
}
// 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.
if let Some(entry) = &mut self.entry
&& !cards.is_empty()
{
entry.cards_arrived(cx.background_executor().now());
}
self.anvil_grid.update(cx, |grid, cx| {
grid.set_cards(cards, cx);
grid.set_shown(shown, cx);
});
self.prepare_others(cx);
}
/// The cards of `rows` during the champ select, each with the reasons it cannot be picked;
/// none outside a champ select.
fn champ_select_cards<'a>(&self, rows: impl Iterator<Item = &'a ChampionRow>) -> Rc<[Card]> {
match self.live_champ_select() {
Some(pick) => rows
.map(|row| Card::from_row(row).with_unpickable(pick.unpickable(row.champion.id)))
.collect(),
None => Rc::new([]),
}
}
/// The rows of « Autres champions »: those whose id is not an Anvil one, in the master
/// order; all of them when the client gave no list.
fn other_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let anvil = self
.live_champ_select()
.and_then(|pick| pick.anvil_champions.as_deref());
self.ordered_rows()
.filter(move |row| anvil.is_none_or(|ids| !ids.contains(&row.champion.id)))
}
/// Builds the cards of « Autres champions », for when the section opens or the champ select
/// or the statistics change; while it is folded, nothing is built.
fn prepare_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let cards = self.champ_select_cards(self.other_rows());
self.others_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
self.refresh_others(cx);
}
/// Recomputes which cards of « Autres champions » its search keeps: the cards are the rows
/// of `other_rows`, in the same order.
pub(in crate::page) fn refresh_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let shown: Vec<usize> = self
.other_rows()
.enumerate()
.filter(|(_, row)| self.others_search.matches(&row.champion))
.map(|(ix, _)| ix)
.collect();
self.others_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// Opens or folds « Autres champions »; folded, it gives its cards back.
pub(in crate::page) fn toggle_others(&mut self, cx: &mut Context<Self>) {
self.others_open = !self.others_open;
if self.others_open {
self.prepare_others(cx);
} else {
self.new_others_grid(cx);
}
cx.notify();
}
/// Folds « Autres champions » and empties its search, for a new champ select.
pub(in crate::page) fn fold_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.others_open {
self.others_open = false;
self.new_others_grid(cx);
}
self.others_search = ChampionSearch::new("");
self.others_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
}
+243
View File
@@ -0,0 +1,243 @@
use crate::card::{Card, Reason};
use crate::card_grid::CardGrid;
use crate::motion::Fade;
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 {
!cx.reduce_motion() && window.is_visible() && !self.covered
}
/// Plays the entry of the champ select waiting for it, if the page is in front: the band of
/// 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() || !self.selection_shown() {
return;
}
if cx.reduce_motion() {
self.entry_waiting = false;
return;
}
if !self.may_animate(window, cx) {
return;
}
self.entry_waiting = false;
let now = cx.background_executor().now();
let mut entry = Entry::new(now);
if !self.anvil_grid.read(cx).cards().is_empty() {
entry.cards_arrived(now);
}
self.entry = Some(entry);
cx.notify();
}
/// The champ select's motion shows its end at once: the window is hidden, the page covered
/// or the setting turned off. A card the pointer waited for is lifted now.
pub(in crate::page) fn end_stage(&mut self, cx: &mut Context<Self>) {
self.entry = None;
self.taken.clear();
self.land_hover(cx.background_executor().now(), cx);
}
/// No entry played or waiting, no card going down or waited for: the champ select ends.
pub(in crate::page) fn forget_stage(&mut self) {
self.entry = None;
self.entry_waiting = false;
self.taken.clear();
self.hover_waiting = None;
}
/// The champ select ended: the hand leaves, the last card first, then the veil of the tabs
/// covers the screen and the end is applied under it (`finish_exit`).
pub(in crate::page) fn start_exit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let now = cx.background_executor().now();
let hand = self.anvil_grid.entity_id();
let lifted: Vec<_> = self.lifts.lifted(hand, now).collect();
// Each card leaves from where it is: on its way, lifted, under the veil or going down
// after an ally's confirmation. Those not dealt yet stay out of sight.
let hand_at = HandAt {
entry: self.entry.filter(Entry::dealing),
lifted: &lifted,
veil: self.lifts.veil(hand, now),
taken: &self.taken,
};
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(veil, veil_from));
self.next_fade_frame(window, cx);
cx.notify();
}
/// Applies the end of the champ select that was leaving: the home comes back as #74 leaves
/// it.
pub(in crate::page) fn finish_exit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.leave = None;
self.change_champ_select(None, window, cx);
}
/// An ally confirmed a champion of the hand: its card goes down to its place, a little
/// lower than the others, as it greys. A card still dealt goes straight to that place.
pub(in crate::page) fn lower_taken(
&mut self,
before: &[Card],
window: &Window,
cx: &mut Context<Self>,
) {
if !self.selection_shown() || !self.may_animate(window, cx) {
return;
}
let now = cx.background_executor().now();
let taken = |card: &Card| card.reasons.contains(&Reason::TakenByAlly);
let lowered: Vec<_> = (self.anvil_grid.read(cx).cards().iter().enumerate())
.filter(|(ix, card)| {
taken(card) && self.entry.is_none_or(|entry| entry.landed(*ix, now))
})
.filter_map(|(_, card)| {
let was = before.iter().find(|was| was.id == card.id)?;
(!taken(was)).then(|| Taken::new(card.id, Rc::new(was.clone()), now))
})
.collect();
for card in lowered {
self.taken.retain(|taken| taken.id != card.id);
self.taken.push(card);
}
cx.notify();
}
/// Whether card `id` of `grid` is the hand's and still on its way there at `now`.
pub(in crate::page) fn dealing(
&self,
grid: &Entity<CardGrid>,
id: u32,
now: Instant,
cx: &App,
) -> bool {
if grid.entity_id() != self.anvil_grid.entity_id() {
return false;
}
let Some(entry) = self.entry else {
return false;
};
// A card under the pointer or the keyboard is drawn: the grid knows where it is.
let ix = grid
.read(cx)
.drawn_cards()
.borrow()
.get(&id)
.map(|drawn| drawn.ix);
ix.is_some_and(|ix| !entry.landed(ix, now))
}
/// The card of the hand the pointer waited for is in its place at `now`: lifted if it is
/// still under the pointer or the keyboard.
fn land_hover(&mut self, now: Instant, cx: &mut Context<Self>) {
let Some(waiting) = self.hover_waiting else {
return;
};
let grid = self.anvil_grid.clone();
if waiting
.id
.is_some_and(|id| self.dealing(&grid, id, now, cx))
{
return;
}
self.hover_waiting = None;
if grid.read(cx).hovered() == waiting.id {
self.hovered(&grid, waiting, cx);
}
}
/// Whether the champ select's motion asks for frames: its entry, a card going down, or a
/// card the pointer waits for, until a frame finds it in its place. Nothing is read on the
/// home or « Statistiques ».
pub(in crate::page) fn stage_moving(&self, cx: &App) -> bool {
if !self.taken.is_empty() || self.hover_waiting.is_some() {
return true;
}
let Some(entry) = self.entry else {
return false;
};
let now = cx.background_executor().now();
entry.animating(self.anvil_grid.read(cx).cards().len(), now)
}
/// Asks for the champ select's next frame, once.
pub(in crate::page) fn next_stage_frame(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.stage_frame_asked {
self.stage_frame_asked = true;
cx.on_next_frame(window, |page, _, cx| page.stage_frame(cx));
}
}
/// One frame of the champ select's motion: what is over is forgotten, a card dealt under
/// the pointer is lifted, and the page draws the rest where it is now.
fn stage_frame(&mut self, cx: &mut Context<Self>) {
self.stage_frame_asked = false;
let now = cx.background_executor().now();
let cards = self.anvil_grid.read(cx).cards().len();
if self.entry.is_some_and(|entry| entry.over(cards, now)) {
self.entry = None;
}
self.taken.retain(|taken| !taken.done(now));
self.land_hover(now, cx);
cx.notify();
}
/// The hand's cards moving over its grid, if any.
pub(in crate::page) fn hand_layer(&self, cx: &App) -> Option<AnyElement> {
// An entry whose hand has no card yet hides none.
let entry = self.entry.filter(Entry::dealing);
if entry.is_none() && self.leave.is_none() && self.taken.is_empty() {
return None;
}
let now = cx.background_executor().now();
let id = self.anvil_grid.entity_id();
let motion = HandMotion {
entry,
leave: self.leave.clone(),
taken: self.taken.clone(),
lifted: self.lifts.lifted(id, now).map(|lifted| lifted.id).collect(),
unveiled: 1. - self.veil(cx),
now,
};
let grid = self.anvil_grid.read(cx);
Some(stage::hand_layer(
grid.cards().clone(),
grid.drawn_cards().clone(),
grid.images().cloned(),
motion,
))
}
/// The title's opacity and how far below its place it is, while the entry brings it in.
pub(in crate::page) fn title_pose(&self, cx: &App) -> Option<(f32, f32)> {
let entry = self.entry?;
Some(entry.title_pose(cx.background_executor().now()))
}
}
+242
View File
@@ -0,0 +1,242 @@
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;
use gpui_kit::component::input::Input;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
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.
pub(in crate::page) fn anvil_line(&self) -> Option<SharedString> {
if let Some(notice) = self.stats_notice() {
return Some(notice.label(self.error().map(String::as_str)));
}
match &self.live_champ_select()?.anvil_champions {
None => Some(UNKNOWN_ANVIL.into()),
Some(ids) if ids.is_empty() => {
Some("Aucun Champion de l'Enclume dans cette sélection".into())
}
Some(_) => None,
}
}
/// « Champions de l'Enclume » with how many there are, and the row of their cards.
pub(in crate::page) fn anvil_area(
&self,
window_width: Pixels,
cx: &mut Context<Page>,
) -> impl IntoElement {
let theme = cx.theme();
let (muted, border) = (theme.muted_foreground, theme.border);
let row = self.anvil_line();
let said_elsewhere = self.stats_notice().is_some_and(StatsNotice::said_elsewhere)
|| row.as_deref() == Some(UNKNOWN_ANVIL);
div()
.v_flex()
.gap_3()
.pr(Scrollbar::width())
.child(
div()
.h_flex()
.items_center()
.gap(px(6.))
.child(heading(cx).text_xl().child("Champions de l'Enclume"))
.when(row.is_none(), |heading| {
heading.child(count_badge(self.anvil_count.clone(), muted, border))
}),
)
.children(match row {
// The header already says there is no Season, and a banner the statistics' error:
// not twice.
Some(_) if said_elsewhere => None,
Some(line) => Some(notice_line("anvil-notice", line, muted)),
None => Some(
div()
.w_full()
.debug_selector(|| "anvil-row".into())
.child(match self.anvil_grid.read(cx).rows_height(window_width) {
Some(height) => self
.anvil_grid
.clone()
.cached(StyleRefinement::default().w_full().h(height))
.into_any_element(),
None => self.anvil_grid.clone().into_any_element(),
})
.children(self.lift_layer(&self.anvil_grid, cx))
.children(self.hand_layer(cx))
.into_any_element(),
),
})
}
/// « Autres champions » when the client gave the Anvil champions, so that these are the ones
/// without an anvil; « Tous les champions » when it did not, as the section then lists all.
pub(in crate::page) fn others_title(&self) -> &'static str {
let known = self
.live_champ_select()
.is_some_and(|pick| pick.anvil_champions.is_some());
if known {
"Autres champions"
} else {
"Tous les champions"
}
}
/// « Autres champions »: a header that folds the section, and open, its search and its
/// cards. Folded, no card is built and the grid is not even drawn. They are the champions
/// without an anvil only when the client gave the list: else they are all of them. The
/// grid is as tall as all its cards, and the champ select's scrolling moves it: it builds
/// only the rows that scrolling has in view of the window (`window_width` gives the cards'
/// size).
pub(in crate::page) fn others_area(
&self,
window_width: Pixels,
cx: &mut Context<Page>,
) -> impl IntoElement {
let theme = cx.theme();
let (muted, border, ring, hover, hover_foreground) = (
theme.muted_foreground,
theme.border,
theme.ring,
theme.accent,
theme.accent_foreground,
);
let title = self.others_title();
let open = self.others_open;
let chevron = if open {
IconName::ChevronDown
} else {
IconName::ChevronRight
};
div()
.v_flex()
.w_full()
.gap_3()
.pr(Scrollbar::width())
.child(
BaseButton::new("others-toggle")
.track_focus(&self.others_focus)
.w_full()
.justify_start()
.gap_2()
.px_1()
.py_2()
.border_t_1()
.border_b_1()
.border_color(border)
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.text_lg()
.accessibility_label(title)
.debug_selector(|| "others-toggle".into())
.child(Icon::new(chevron).small().text_color(muted))
.child(heading(cx).child(title))
.on_click(cx.listener(|this, _, _, cx| this.toggle_others(cx))),
)
.when(open, |section| {
section
.child(
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
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)),
)
.child(self.others_cards(window_width, cx))
.children(self.lift_layer(&self.others_grid, cx))
})
}
/// The grid of « Autres champions », and where it starts in the page's scrolling, which it
/// reads to know its rows in view: recorded after each layout, and the grid is drawn again
/// when that place changes.
fn others_cards(&self, window_width: Pixels, cx: &mut Context<Page>) -> impl IntoElement {
let grid = self.others_grid.clone();
// Cached, as the home's grid: hovering elsewhere does not draw its cards again. Its size
// comes from this style, all its rows tall (an empty one says so, in its own height).
let shown = match grid.read(cx).rows_height(window_width) {
Some(height) => grid
.clone()
.cached(StyleRefinement::default().w_full().h(height))
.into_any_element(),
None => grid.clone().into_any_element(),
};
let (paging, grid) = (self.paging.clone(), grid.downgrade());
div()
.w_full()
.on_children_prepainted(move |bounds, window, cx| {
let Some(bounds) = bounds.first() else { return };
let (scroll, top) = (&paging.scroll, &paging.top);
let now = bounds.origin.y - scroll.bounds().origin.y - scroll.offset().y;
if top.get().is_none_or(|was| (was - now).abs() > px(0.5)) {
top.set(Some(now));
// The grid built its rows from the former place: it is drawn again, once this
// draw is over, as a change noted during a draw dirties nothing for the next.
let grid = grid.clone();
window.defer(cx, move |_, cx| {
grid.update(cx, |_, cx| cx.notify()).ok();
});
}
})
.child(shown)
}
}
+196
View File
@@ -0,0 +1,196 @@
use super::{PAGE_PADDING, Page, Tab, shown};
use crate::stage;
use crate::text::{CLIENT_ABSENT, official_differs};
#[cfg(test)]
use arena_tracker_core::{ChampionSort, StateFilter};
use arena_tracker_core::{ProgressCheck, UpdateProblem};
use gpui_kit::component::alert::Alert;
use gpui_kit::component::select::Select;
use gpui_kit::component::{ActiveTheme as _, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
impl Page {
/// One line each, the most important first; the stored data stays visible under all.
fn status_alerts(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
if let Some(problem) = &self.status.problem {
let message = problem.message();
banners.push(match problem {
UpdateProblem::MatchPending | UpdateProblem::NoAccount => {
Alert::warning("problem", message)
}
_ => 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",
official_differs(*app, *official),
));
}
if !self.pending_round && !self.status.client_running {
banners.push(Alert::info("client", CLIENT_ABSENT));
}
if let Some(notice) = &self.notice {
banners.push(Alert::warning("notice", notice.clone()));
}
if let Some(error) = self.error() {
banners.push(Alert::error("stats", error.clone()));
}
banners
.into_iter()
.map(|alert| alert.small().into_any_element())
.collect()
}
/// The veil's opacity over the screen shown, 0 at rest.
pub(in crate::page) fn veil(&self, cx: &App) -> f32 {
self.fade
.as_ref()
.map_or(0., |fade| fade.veil(cx.background_executor().now()))
}
#[cfg(test)]
pub(crate) fn champion_sort(&self) -> Option<ChampionSort> {
self.champion_sort
}
#[cfg(test)]
pub(crate) fn home_filter(&self) -> StateFilter {
self.home_filter
}
}
impl Render for Page {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// 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.playback_visible(window) {
self.end_match(cx);
} else {
// 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 splash = self.banner_splash();
let own = self.banner_champion() == Some(animation.champion_id);
self.banner_art.update(cx, |art, cx| {
if own {
art.reveal(splash, cx);
} else {
art.set_target(splash, cx);
}
});
}
window.request_animation_frame();
}
}
self.lifts.tidy(now);
if self.lifts.animating(now) {
window.request_animation_frame();
}
if self.stage_moving(cx) {
self.next_stage_frame(window, cx);
}
let sweep = (self.entry)
.and_then(|entry| entry.sweep(now))
.map(|progress| stage::sweep(progress, window.viewport_size(), cx));
let muted = cx.theme().muted_foreground;
let status_line = self.status_line(now);
div()
// The pointer takes over from the keyboard: the card it lifted goes down.
.on_mouse_move(cx.listener(|page, _: &MouseMoveEvent, _, cx| {
if let Some(grid) = page.lifted_by_keyboard.take().and_then(|g| g.upgrade()) {
grid.update(cx, |grid, cx| grid.put_down(cx));
}
}))
.relative()
.v_flex()
.size_full()
.gap_3()
.p(px(PAGE_PADDING))
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the status
// wraps onto a second line: nothing is ever clipped.
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.child(self.navigation(cx))
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The phases are about the signed-in Account.
.disabled(self.in_phase())
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
})),
)
.child(
div().h_flex().items_center().gap_3().flex_shrink_0().child(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
),
),
)
})
.children(self.friend_field(cx))
.when(shown("banners"), |page| {
page.child(div().v_flex().gap_1().children(self.status_alerts()))
})
.child(
// The screen under the header, which does not move: the veil of the transition
// covers it alone.
div()
.relative()
.v_flex()
.flex_1()
.min_h_0()
.gap_3()
.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));
screen.child(div().absolute().inset_0().bg(veil))
}),
)
// The band of light of a champ select's entry, over the whole window.
.children(sweep)
}
}
+128
View File
@@ -0,0 +1,128 @@
//! 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;
use arena_tracker_core::{Account, ProgressCheck, Scope, SeasonScope, StateFilter};
use gpui_kit::*;
impl Page {
/// « 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()
.and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid))
.or(self.status.updating.as_ref())
.or(self.last_active.as_ref())
.or(self.accounts.first())
}
/// 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);
self.show_import(true, 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_phase() {
let puuid = self.phase_account.as_deref()?;
return self.accounts.iter().find(|a| a.puuid == puuid);
}
self.viewed()
}
/// Whether the Account shown is not the one being updated (or none is), so only stored
/// data is shown. Unknown until the follower's first round has reported.
pub(in crate::page) fn stale(&self) -> bool {
!self.pending_round
&& self.displayed().is_some_and(|viewed| {
self.status
.updating
.as_ref()
.is_none_or(|updating| updating.puuid != viewed.puuid)
})
}
/// The game's own count, only meaningful for the Account being updated in the current Season,
/// 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.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)
}
/// The tab's own statistics error: the home may have computed its own.
pub(in crate::page) fn error(&self) -> Option<&String> {
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 {
Scope {
season: self.season.clone(),
format: self.format,
}
}
}
+386
View File
@@ -0,0 +1,386 @@
//! 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::import_view::wait_until;
use super::{AccountItem, AccountList, Page, RELOAD_EVERY};
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.
refusal: Option<String>,
/// 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 relay's quota is 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 last progress of the import running.
progress: Option<SyncProgress>,
/// The Friend whose last import failed, and why.
error: Option<(String, String)>,
}
impl Friends {
/// The puuid of the Friend whose import runs.
pub(super) fn import_running(&self) -> Option<&str> {
self.import.running.as_deref()
}
/// The last progress of the import running, if it has told one.
pub(super) fn import_progress(&self) -> Option<SyncProgress> {
self.import.progress
}
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) => self.friends.refusal = Some(refused.message()),
}
}
/// Imports the Matches of the Friend `puuid` not stored yet, now or when the import running
/// has ended.
pub(in crate::page) fn import_friend(&mut self, puuid: &str, cx: &mut Context<Self>) {
let import = &mut self.friends.import;
match &import.running {
Some(running) if running == puuid => import.queued = None,
Some(_) => import.queued = Some(puuid.to_string()),
None => self.start_friend_import(puuid.to_string()),
}
cx.notify();
}
fn start_friend_import(&mut self, puuid: String) {
let import = &mut self.friends.import;
import.error.take_if(|(failed, _)| *failed == puuid);
import.queued = None;
import.progress = None;
import.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>,
) {
let puuid = self.current_puuid(puuid, window, cx);
let puuid = puuid.as_str();
if self.friends.import.running.as_deref() != Some(puuid) {
return;
}
let now = cx.background_executor().now();
self.import_view.friend_until = wait_until(progress, now);
self.friends.import.progress = Some(progress);
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 puuid = self.current_puuid(&puuid, window, cx);
let import = &mut self.friends.import;
import.running = None;
import.line = None;
import.progress = None;
if let Err(message) = outcome {
import.error = Some((puuid.clone(), message));
}
if self.shows(&puuid) {
self.reload_in_background(window, cx);
}
if let Some(next) = self.friends.import.queued.take() {
self.start_friend_import(next);
}
}
/// What an import message names may have changed PUUID since the import started (a new Riot
/// key, `Tracker::replaced_puuid`): the Accounts are read again, so the page follows it.
fn current_puuid(
&mut self,
puuid: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> String {
let Some(new) = self.tracker.replaced_puuid(puuid) else {
return puuid.into();
};
if self.friends.import.running.as_deref() == Some(puuid) {
self.reload_accounts(window, cx);
}
new
}
/// The PUUIDs the page holds follow the ones that replaced them (see `current_puuid`), so
/// the Account shown stays the same.
pub(in crate::page) fn follow_replaced_puuids(&mut self) {
let import = &mut self.friends.import;
let held = [
self.pinned.as_mut(),
import.running.as_mut(),
import.queued.as_mut(),
import.error.as_mut().map(|(puuid, _)| puuid),
];
for puuid in held.into_iter().flatten() {
if let Some(new) = self.tracker.replaced_puuid(puuid) {
*puuid = new;
}
}
}
/// 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);
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.clone())
.map(|message| div().text_sm().text_color(danger).child(message)),
)
.into_any_element(),
)
}
}
#[cfg(test)]
mod tests;
+366
View File
@@ -0,0 +1,366 @@
//! 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.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);
}
// The relay is down: trying again later may work.
handles.relay_down.store(true, Ordering::SeqCst);
add(&page, &mut window, "Carl#EUW");
cx.condition(&page, |p, _| !p.friends.pending).await;
assert_eq!(
refusal(&page, &mut window).as_deref(),
Some("Le service Arena Tracker est indisponible : réessayez plus tard.")
);
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)]);
});
}
#[gpui::test]
async fn a_friend_shown_while_its_puuid_changes_stays_shown_and_its_import_goes_on(
cx: &mut TestAppContext,
) {
let (page, mut window, handles) = on_carl(cx).await;
handles.new_key.store(true, Ordering::SeqCst);
handles.third.store(true, Ordering::SeqCst);
handles.gate.set(false);
// Chosen again, Carl is rekeyed before its new Match is awaited.
pick(&page, &mut window, "Carl");
cx.condition(&page, |p, _| p.pinned.as_deref() == Some("Carl2"))
.await;
page.read_with(&window, |p, _| {
assert_eq!(p.friends.import.running.as_deref(), Some("Carl2"));
assert_eq!(p.viewed().map(|a| a.puuid.as_str()), Some("Carl2"));
assert_eq!(
p.friend_status().as_deref(),
Some("Import de Carl : 0 / 1 Parties")
);
});
assert_eq!(selected(&page, &mut window).as_deref(), Some("Carl2"));
handles.gate.set(true);
imported(&page, cx, 3).await;
assert_eq!(status_line(&page, &mut window), None);
page.read_with(&window, |p, _| {
assert_eq!(p.pinned.as_deref(), Some("Carl2"));
assert!(p.friends.ids.contains("Carl2") && p.friend_error().is_none());
});
}
+274
View File
@@ -0,0 +1,274 @@
//! The « Défi » tab, the home: the Challenge of one Season, and its champions.
use arena_tracker_core::{SeasonScope, StateFilter, Statistics};
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
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.
pub(in crate::page) const FILTERS: [(&str, StateFilter); 3] = [
("Tous", StateFilter::All),
("Restants", StateFilter::Remaining),
("Validés", StateFilter::Completed),
];
const NO_SEASON: &str = "Aucune Saison en cours";
/// Why the home has no statistics to browse yet. The home and the champ select say it the same
/// way (`label`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(in crate::page) enum StatsNotice {
/// There is no Season to read: the banner already says so.
NoSeason,
/// No Account to read.
NoAccount,
/// The statistics job has not returned yet.
Loading,
/// The job failed: the banner already says so.
Error,
}
impl StatsNotice {
/// The French text, `error` being the statistics' error for `Error`.
pub(in crate::page) fn label(self, error: Option<&str>) -> SharedString {
match self {
Self::NoSeason => NO_SEASON.into(),
Self::NoAccount => "Compte indisponible".into(),
Self::Loading => "Chargement des statistiques…".into(),
Self::Error => error.unwrap_or_default().to_string().into(),
}
}
/// Whether something else on the page already says it: the notice stays silent then.
pub(in crate::page) fn said_elsewhere(self) -> bool {
matches!(self, Self::NoSeason | Self::Error)
}
}
/// A sober line in muted text, for what stands in place of the cards.
pub(in crate::page) fn notice_line(
selector: &'static str,
text: SharedString,
muted: Hsla,
) -> AnyElement {
div()
.text_sm()
.text_color(muted)
.debug_selector(move || selector.into())
.child(text)
.into_any_element()
}
/// The small bordered count beside a heading.
pub(in crate::page) fn count_badge(
count: SharedString,
muted: Hsla,
border: Hsla,
) -> impl IntoElement {
div()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(border)
.rounded(px(6.))
.text_xs()
.text_color(muted)
.child(count)
}
impl Page {
/// Whether one Season is selected, rather than all of them: only a Season has a Challenge.
pub(in crate::page) fn in_season(&self) -> bool {
matches!(self.season, SeasonScope::Season(_))
}
/// What the home reads: its own statistics when its scope differs, else the Statistics tab's.
pub(in crate::page) fn home_statistics(&self) -> Option<&Statistics> {
self.home_season.as_ref()?;
match self.home_scope {
Some(_) => self.home_stats.as_ref(),
None => self.stats.as_ref(),
}
}
/// Why the home has no statistics to show yet, if it has none: the same for the Défi tab
/// and the champ select. Cheap enough to ask at each render.
pub(in crate::page) fn stats_notice(&self) -> Option<StatsNotice> {
if self.error().is_some() {
return Some(StatsNotice::Error);
}
if self.home_statistics().is_some() {
return None;
}
if self.home_season.is_none() {
return Some(StatsNotice::NoSeason);
}
// 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()
};
Some(if no_account {
StatsNotice::NoAccount
} else {
StatsNotice::Loading
})
}
/// 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>,
) -> Div {
let column = div()
.v_flex()
.flex_1()
.min_h_0()
.w_full()
.max_w(px(MAX_WIDTH))
.mx_auto()
.gap_3();
if shown("banner") {
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 => {
if shown("home-tools") {
column = column.child(self.home_heading(cx));
}
if shown("cards") {
// Cached: only a change to the cards, the filter, the search or a
// scroll over them draws the grid again; the card hovered is drawn
// lifted over it. Its size comes from this style.
column = column
.child(self.home_grid.clone().cached(
StyleRefinement::default().w_full().flex_1().min_h(px(240.)),
))
.children(self.lift_layer(&self.home_grid, cx));
}
}
// Without statistics the heading would count « 0 » and the grid would say no
// champion matches: say why there are no cards instead (the banner has the
// error, the header the missing Season).
Some(notice) if notice.said_elsewhere() => {}
Some(notice) => {
let muted = cx.theme().muted_foreground;
column = column.child(notice_line(
"home-notice",
notice.label(self.error().map(String::as_str)),
muted,
));
}
}
}
// In a low window the banner leaves the grid less than its least height: the column
// scrolls then, as the champ select's does.
vec![column.id("home").overflow_y_scroll().into_any_element()]
}
/// The sort selector: a sort icon and the choice, « Maîtrise » or « A–Z ». It is on the
/// home and in « Autres champions »; the Anvil champions are always A to Z.
pub(in crate::page) fn sort_selector(&self, cx: &App) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
div()
.h_flex()
.items_center()
.gap_1()
.debug_selector(|| "sort".into())
.child(Icon::new(IconName::SortAscending).small().text_color(muted))
.child(
Select::new(&self.sort_select)
.id("sort")
.accessibility_label("Trier les cartes")
.w(px(140.))
.min_w(px(110.)),
)
}
/// « Mes champions » with how many cards are shown, and on the right the search, the filters
/// and the sort, as the mockup's `.tools`.
fn home_heading(&self, cx: &mut Context<Page>) -> impl IntoElement {
let theme = cx.theme();
let (muted, border) = (theme.muted_foreground, theme.border);
let selected = FILTERS.iter().position(|(_, f)| *f == self.home_filter);
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.debug_selector(|| "home-tools".into())
.child(
div()
.h_flex()
.items_center()
.gap(px(6.))
.child(heading(cx).text_xl().child("Mes champions"))
.child(count_badge(self.home_shown_count.clone(), muted, border)),
)
.child(
div()
.h_flex()
.items_center()
.gap_3()
.child(
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")
.pill()
.selected_index(selected.unwrap_or(0))
.children(FILTERS.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = FILTERS.get(*ix) {
this.home_filter = *filter;
this.home_filtered(cx);
cx.notify();
}
})),
)
.child(self.sort_selector(cx)),
)
}
}
+404
View File
@@ -0,0 +1,404 @@
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::{Line, NO_SEASON, Page};
use crate::banner_art::BannerArt;
use crate::motion::{COUNTER_ROLL, ease_out};
use crate::page::Tab;
use crate::theme::{banner_band, gold_ink, heading};
impl Page {
/// 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(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, 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.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),
theme.muted_foreground,
theme.foreground,
gold_ink(theme),
);
let name = |line: &Line| {
StyledText::new(line.text.clone()).with_highlights([(
line.bold.clone(),
HighlightStyle {
color: Some(foreground),
font_weight: Some(FontWeight::SEMIBOLD),
..Default::default()
},
)])
};
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)))
// 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()
.gap(px(3.))
.child({
let title = StyledText::new(text.title.text.clone()).with_highlights([(
text.title.bold.clone(),
HighlightStyle {
// Rolling, the count is drawn over its place.
color: Some(ink.opacity(if roll.is_some() { 0. } else { 1. })),
..Default::default()
},
)]);
let rolling = roll.map(|t| {
rolling_count(title.layout().clone(), text.title.clone(), ink, t)
});
heading(cx)
.relative()
.mt(px(8.))
.mb(px(7.))
// The champ select's title comes in, rising, at its entry.
.when_some(self.title_pose(cx), |title, (opacity, below)| {
title.opacity(opacity).relative().top(px(below))
})
.text_size(px(layout.title))
.line_height(relative(1.12))
.debug_selector(|| "banner-title".into())
.child(title)
.children(rolling)
})
// 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.))
.map_or(1., |t| (t / COUNTER_ROLL).min(1.)),
)
.text_sm()
.text_color(muted)
.child(name(line))
}))
.into_any_element()
}));
div()
.relative()
.flex()
.w_full()
.flex_shrink_0()
.min_h(px(layout.min_height))
.rounded(px(RADIUS))
.overflow_hidden()
.bg(band)
.map(|banner| {
if layout.narrow {
banner.flex_col().items_start()
} else {
banner.flex_row().items_center()
}
})
.gap(px(layout.gap))
.px(px(layout.padding))
.py(px(BANNER_PADDING_Y))
.debug_selector(|| "banner".into())
.child(self.banner_art.clone())
// 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.;
/// The banner's measures, from the window width as the reference page's `clamp` and `vw` give
/// them.
#[derive(Clone, Copy, Debug, PartialEq)]
struct BannerLayout {
/// At most 680 px: the ring goes above the text.
narrow: bool,
min_height: f32,
gap: f32,
padding: f32,
ring: f32,
title: f32,
}
impl BannerLayout {
fn of(window_width: Pixels) -> BannerLayout {
let vw = window_width.as_f32() / 100.;
BannerLayout {
narrow: window_width.as_f32() <= 680.,
min_height: (26. * vw).clamp(220., 310.),
gap: (3. * vw).clamp(16., 40.),
padding: (3. * vw).clamp(16., 36.),
ring: (16. * vw).clamp(120., 200.),
title: (2.8 * vw).clamp(22., 34.),
}
}
}
/// The count at the start of `title`, `t` (0 to 1) into its roll: it rises from 10 px below its
/// place and fades in, painted over the title laid out with it transparent (`layout`). The text
/// style is the title's own, which the element inherits.
fn rolling_count(layout: TextLayout, title: Line, ink: Hsla, t: f32) -> impl IntoElement {
canvas(
|_, _, _| {},
move |_, _, window, cx| {
let Some(origin) = layout.position_for_index(title.bold.start) else {
return;
};
let style = window.text_style();
let font_size = style.font_size.to_pixels(window.rem_size());
let count = title.text[title.bold.clone()].to_string();
let run = TextRun {
len: count.len(),
font: style.font(),
color: ink.opacity(t),
background_color: None,
underline: None,
strikethrough: None,
};
let line = window
.text_system()
.shape_line(count.into(), font_size, &[run], None);
let rise = px(10. * (1. - ease_out(t)));
let _ = line.paint(
origin + point(px(0.), rise),
layout.line_height(),
TextAlign::Left,
None,
window,
cx,
);
},
)
.absolute()
.inset_0()
}
/// The splash, framed on the champion (#83), in the banner's illustration area: its right 72 %,
/// or all of it in a narrow window. It fades into the band on the text's side.
impl Render for BannerArt {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(splash) = self.target.clone() else {
self.release(window, cx);
return div().absolute().into_any_element();
};
let layout = BannerLayout::of(window.viewport_size().width);
let band = banner_band(cx.theme());
let art = cx.entity();
let corners = if layout.narrow {
Corners::all(px(RADIUS))
} else {
Corners {
top_right: px(RADIUS),
bottom_right: px(RADIUS),
..Corners::default()
}
};
let reveal = self.reveal_frame(window, cx);
let layer = |previous: bool| {
let art = art.clone();
let splash = splash.clone();
canvas(
|_, _, _| {},
move |bounds, _, window, cx| {
// Scrolled entirely out of the column (a low window): nothing to show, so nothing
// decoded nor held, and it comes back with the banner.
let visible = bounds.intersect(&window.content_mask().bounds);
if visible.size.width <= Pixels::ZERO || visible.size.height <= Pixels::ZERO {
art.update(cx, |art, cx| art.release(window, cx));
return;
}
let image = if previous {
art.read(cx).previous_image()
} else {
art.update(cx, |art, cx| art.image(&splash, cx))
};
let Some((image, focus)) = image else {
return;
};
let frame =
focus.banner_frame(bounds.size.width.as_f32(), bounds.size.height.as_f32());
let zoom = if previous { 1. } else { reveal.zoom };
let frame = Bounds {
origin: bounds.origin + point(px(frame.left * zoom), px(frame.top * zoom))
- point(bounds.size.width, bounds.size.height) * ((zoom - 1.) / 2.),
size: size(px(frame.width * zoom), px(frame.height * zoom)),
};
let _ = window.paint_image(bounds, frame, corners, image, 0, false);
},
)
.size_full()
};
let area = div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.debug_selector(|| "banner-art".into())
.child(layer(false).opacity(reveal.opacity))
.children(self.previous_opacity(window, cx).map(|opacity| {
div()
.absolute()
.inset_0()
.opacity(opacity)
.child(layer(true))
}));
// A layer of the band over the splash, from `from` to `to` opacity in the gradient's
// direction (`angle`: 0 to the top, 90 to the right, 180 to the bottom).
let fade = |angle: f32, (from, at): (f32, f32), to: f32| {
div().absolute().bg(linear_gradient(
angle,
linear_color_stop(band.opacity(from), at),
linear_color_stop(band.opacity(to), 1.),
))
};
if layout.narrow {
// From the bottom: the band, then a fade to the splash at the top.
area.left_0()
.child(
fade(180., (0., 0.), 0.4)
.left_0()
.right_0()
.top_0()
.h(relative(0.25)),
)
.child(
fade(180., (0.4, 0.), 1.)
.left_0()
.right_0()
.top(relative(0.25))
.h(relative(0.35)),
)
.child(
fade(180., (1., 0.), 1.)
.left_0()
.right_0()
.bottom_0()
.h(relative(0.4))
.rounded_b(px(RADIUS)),
)
.into_any_element()
} else {
// The banner's fade, solid to its 30 %, 72 % at its 46 %, none from its 74 %, in the
// area that starts at its 28 %; and a lighter one from the bottom.
area.w(relative(0.72))
.child(
fade(90., (1., 0.11), 0.72)
.top_0()
.bottom_0()
.left_0()
.w(relative(0.25)),
)
.child(
fade(90., (0.72, 0.), 0.)
.top_0()
.bottom_0()
.left(relative(0.25))
.w(relative(0.39)),
)
.child(
fade(0., (0.55, 0.), 0.)
.left_0()
.right_0()
.bottom_0()
.h(relative(0.45))
.rounded_br(px(RADIUS)),
)
.into_any_element()
}
}
}
+211
View File
@@ -0,0 +1,211 @@
use std::ops::Range;
use std::rc::Rc;
use arena_tracker_core::{ChampionRow, MatchOutcome, Splash, Statistics};
use gpui_kit::SharedString;
use crate::page::champ_select::UNKNOWN_ANVIL;
use crate::text::{attempt_ordinal, ordinal, short_date};
/// A line of the banner, the champion's name (or the count) set apart.
#[derive(Clone, Debug, Default, PartialEq)]
pub(in crate::page) struct Line {
pub(in crate::page) text: SharedString,
pub(in crate::page) bold: Range<usize>,
}
impl Line {
/// `before`, then `bold`, then `after`.
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(),
}
}
fn plain(text: &str) -> Line {
Line {
text: text.to_owned().into(),
bold: 0..0,
}
}
}
/// The Season as both banners' overline writes it: upper case, and a default split Season, named
/// « Saison 2 2026 » in the stored data, as « SAISON 2 · 2026 ».
fn overline(season: &SharedString) -> String {
let season = season.to_uppercase();
if let Some((split, year)) = season.rsplit_once(' ')
&& year.len() == 4
&& year.bytes().all(|b| b.is_ascii_digit())
&& split
.strip_prefix("SAISON ")
.is_some_and(|n| n.parse::<u32>().is_ok())
{
return format!("{split} · {year}");
}
season
}
/// What the banner shows, prepared when the home statistics change: it follows the home's Season,
/// never the Format, the filter nor the search.
#[derive(Clone, Debug, Default, PartialEq)]
pub(in crate::page) struct BannerContent {
/// The Season, as the overline writes it; empty without a Season.
pub(in crate::page) season: SharedString,
/// The home counter or the champ select title.
pub(in crate::page) title: Line,
/// Last completion at home, Anvil availability during champ select.
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 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>,
known: bool,
count: usize,
splash: Option<Rc<Splash>>,
) -> Self {
let season = overline_with_count(season, stats);
let detail = if !known {
Line::plain(UNKNOWN_ANVIL)
} else if stats.is_some() {
// 0 and 1 take the singular in French.
let available = if count > 1 {
" à valider et disponibles"
} else {
" à valider et disponible"
};
Line::new("Champions de l'Enclume · ", &count.to_string(), available)
} else {
Line::default()
};
Self {
season: season.into(),
title: Line::plain("Sélection des champions"),
detail,
last_match: None,
splash,
}
}
pub(in crate::page) fn new(
season: Option<&SharedString>,
stats: Option<&Statistics>,
) -> BannerContent {
let season = season.map_or_else(SharedString::default, |name| overline(name).into());
let Some((stats, challenge)) = stats.and_then(|s| Some((s, s.challenge.as_ref()?))) else {
return BannerContent {
season,
..BannerContent::default()
};
};
let row = |id: u32| stats.rows.iter().find(|row| row.champion.id == id);
let last = challenge.completion_order.last().and_then(|&id| row(id));
let detail = match last {
Some(row) => {
let day = row
.challenge
.and_then(|c| c.completed_on)
.map(|day| format!(", le {}", short_date(day)))
.unwrap_or_default();
Line::new("Dernier champion validé : ", &row.champion.name, &day)
}
None => Line::plain("Aucun champion validé pour l’instant."),
};
let last_match = challenge.last_match.and_then(|m| {
let name = &row(m.champion_id)?.champion.name;
let detail = match m.outcome {
MatchOutcome::Attempt(n) => format!(" · {} Tentative", attempt_ordinal(n)),
MatchOutcome::Completed(1) => " · validé du premier coup".into(),
MatchOutcome::Completed(n) => format!(" · validé en {n} Tentatives"),
MatchOutcome::AfterCompletion => String::new(),
};
Some(Line::new(
"Dernière Partie : ",
name,
&format!(", {}{detail}", ordinal(m.placement)),
))
});
let count = challenge.completed.to_string();
BannerContent {
season,
title: Line {
text: format!("{count} / {} champions validés", challenge.total).into(),
bold: 0..count.len(),
},
detail,
last_match,
splash: challenge
.last_match
.and_then(|m| row(m.champion_id)?.splash.clone())
.map(Rc::new),
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! The home's own statistics: the scope it computes them for, and what was computed.
use arena_tracker_core::{Scope, SeasonScope, Statistics};
use crate::page::Page;
impl Page {
/// The Season of the home's Challenge, and the scope to compute for it when the Statistics
/// tab's does not already cover it. The Format never applies to the home.
pub(in crate::page) fn settle_home_scope(&mut self) {
let season = match &self.season {
SeasonScope::Season(name) => Some(name),
// A Challenge belongs to one Season: the current one stands in.
SeasonScope::AllSeasons => self.current_season.as_ref(),
};
self.home_season = season.map(|name| name.clone().into());
let home = season.map(|name| Scope {
season: SeasonScope::Season(name.clone()),
format: None,
});
self.home_scope = home.filter(|home| *home != self.statistics_scope());
}
/// Keeps what was computed for the home's own scope, if it had one, and for which Account.
pub(in crate::page) fn set_home_result(
&mut self,
home: Option<Box<Result<Statistics, String>>>,
) {
self.home_computed = home
.as_ref()
.and_then(|_| self.shown.clone().zip(self.home_scope.clone()));
(self.home_stats, self.home_error) = match home.map(|result| *result) {
Some(Ok(stats)) => (Some(stats), None),
Some(Err(error)) => (None, Some(error)),
None => (None, None),
};
}
pub(in crate::page) fn forget_home(&mut self) {
self.home_stats = None;
self.home_error = None;
self.home_computed = None;
}
/// Whether the home's own statistics were computed for the Account and scope it has now.
pub(in crate::page) fn home_is_current(&self) -> bool {
match (&self.shown, &self.home_scope, &self.home_computed) {
(Some(puuid), Some(scope), Some((computed_puuid, computed_scope))) => {
puuid == computed_puuid && scope == computed_scope
}
_ => false,
}
}
}
+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));
}
}
+161
View File
@@ -0,0 +1,161 @@
use super::{Page, Tab};
use crate::card_grid::{CardGrid, CardHovered, PutDown};
use crate::card_lift::{Changes, Changing};
use crate::motion::MatchEnd;
use gpui_kit::*;
impl Page {
/// Lifts the card under the pointer or the keyboard in `grid`, and lights its ring's tick.
/// A wheel over the grid drops its cards at once.
pub(in crate::page) fn light_on_hover(
grid: &Entity<CardGrid>,
cx: &mut Context<Self>,
) -> [Subscription; 2] {
[
cx.subscribe(grid, |this, grid, hovered: &CardHovered, cx| {
let mut hovered = *hovered;
if grid.entity_id() == this.anvil_grid.entity_id() {
this.hover_waiting = None;
}
// A card of the hand still dealt is taken into account once in its place.
let now = cx.background_executor().now();
let waiting = hovered
.id
.is_some_and(|id| this.dealing(&grid, id, now, cx));
if waiting {
this.hover_waiting = Some(hovered);
hovered.id = None;
}
this.hovered(&grid, hovered, cx);
// The pointer moving puts the card the keyboard waits for down, as a lifted
// one: it is not lifted once in its place.
if waiting && hovered.by_keyboard {
this.lifted_by_keyboard = Some(grid.downgrade());
}
}),
cx.subscribe(grid, |this, grid, _: &PutDown, cx| {
this.lifts.drop_grid(grid.entity_id());
cx.notify();
}),
]
}
/// The card under the pointer or the keyboard in `grid` changed: it is lifted, and its tick
/// lit.
pub(in crate::page) fn hovered(
&mut self,
grid: &Entity<CardGrid>,
hovered: CardHovered,
cx: &mut Context<Self>,
) {
let CardHovered { id, by_keyboard } = hovered;
if by_keyboard && id.is_some() {
self.lifted_by_keyboard = Some(grid.downgrade());
} else if (self.lifted_by_keyboard.as_ref())
.is_some_and(|lifted| lifted.entity_id() == grid.entity_id())
{
self.lifted_by_keyboard = None;
}
self.lift(grid, id, cx);
self.light(grid.entity_id(), id, cx);
}
/// The card under the pointer or the keyboard in `grid` is now `id`: it rises over the grid,
/// and the one it replaces settles back. With the Windows « Show animations » setting off,
/// each is where it goes at once.
fn lift(&mut self, grid: &Entity<CardGrid>, id: Option<u32>, cx: &mut Context<Self>) {
// The hand leaving at the end of a champ select lifts nothing.
if self.leave.is_some() {
return;
}
let now = cx.background_executor().now();
let hand = grid.read(cx).is_hand();
self.lifts.hover(grid.entity_id(), id, hand, now);
if cx.reduce_motion() {
self.lifts.finish(now);
}
cx.notify();
}
/// The cards lifted over `grid`, if any: drawn after it, as long as it is.
pub(in crate::page) fn lift_layer(
&self,
grid: &Entity<CardGrid>,
cx: &App,
) -> Option<AnyElement> {
let now = cx.background_executor().now();
let id = grid.entity_id();
let mut lifted: Vec<_> = self.lifts.lifted(id, now).collect();
// The card of the champion changes in place; once the comet lands, « Validé » is the
// grid's own card.
let changing = (self.playback.animation)
.filter(|a| id == self.home_grid.entity_id() && a.end != MatchEnd::Nothing)
.and_then(|a| {
let since_landing = a.since_landing(now);
let before = self.playback.previous_card.clone()?;
if since_landing >= 0. && a.has_comet() {
return None;
}
if !lifted.iter().any(|card| card.id == before.id) {
lifted.insert(
0,
crate::card_lift::Lifted {
id: before.id,
progress: 0.,
},
);
}
Some(Changing {
before,
since_landing,
})
});
let veil = self.lifts.veil(id, now);
if lifted.is_empty() && veil == 0. {
return None;
}
// A lifted card of the hand an ally just took goes down as it greys all the same.
let hand = id == self.anvil_grid.entity_id();
let lowered = (self.taken.iter())
.filter(|taken| hand && lifted.iter().any(|lifted| lifted.id == taken.id))
.map(|taken| taken.lowered(now))
.collect();
let grid = grid.read(cx);
Some(crate::card_lift::layer(
grid.cards().clone(),
grid.drawn_cards().clone(),
grid.images().cloned(),
lifted,
changing.map_or(Changes::Taken(lowered), Changes::Match),
veil,
!cx.reduce_motion(),
))
}
/// The card under the pointer in `grid` changed to `id`. The tick follows the grid that lit
/// it: another grid saying that none of its cards is under the pointer (the pointer went from
/// it to this one, or it was folded) leaves the tick lit.
pub(in crate::page) fn light(
&mut self,
grid: EntityId,
id: Option<u32>,
cx: &mut Context<Self>,
) {
match id {
Some(_) => self.lit_by = Some(grid),
None if self.lit_by == Some(grid) => self.lit_by = None,
None => return,
}
if id.is_none() && grid == self.home_grid.entity_id() {
self.release_home(cx);
}
// 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);
}
}
}
+163
View File
@@ -0,0 +1,163 @@
//! What an import shows beyond its count (#140): the arc around the ring and the status line's
//! countdown while the Riot quota makes it wait. No timer runs outside a wait, and the ring is
//! told at most once a second (rule #1).
use std::time::{Duration, Instant};
use arena_tracker_core::{SyncProgress, account_riot_id};
use gpui_kit::*;
use super::Page;
use crate::text::{quota_line, sync_line};
/// An import of fewer Matches than this shows no arc: a short sync must not flash it.
const ARC_FROM: usize = 10;
const EVERY: Duration = Duration::from_secs(1);
#[derive(Default)]
pub(super) struct ImportView {
/// When the quota wait told by the own sync, or by the Friend's import, ends.
pub(super) own_until: Option<Instant>,
pub(super) friend_until: Option<Instant>,
/// The countdown's timer, while a wait is on: dropped, it stops.
counting: Option<Task<()>>,
/// The signed-in Riot ID and the puuid of the Account it names, once resolved: forgotten
/// when the Accounts are read again.
pub(super) signed_in: Option<(std::sync::Arc<str>, Option<String>)>,
/// What the ring was given last, and when.
arc: Option<(usize, usize)>,
arc_at: Option<Instant>,
}
/// When the wait `progress` tells ends, from `now`.
pub(super) fn wait_until(progress: SyncProgress, now: Instant) -> Option<Instant> {
progress.quota_wait.map(|wait| now + wait)
}
impl Page {
/// The header's status line: the quota wait, else the import or sync going on, else the
/// last result.
pub(super) fn status_line(&self, now: Instant) -> SharedString {
if let Some(secs) = self.quota_secs_left(now) {
return quota_line(secs).into();
}
let busy = self.busy();
(!busy)
.then(|| self.friend_status())
.flatten()
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into())
}
/// The seconds left, rounded up, of the quota wait the status line tells: the own sync's,
/// which comes first as its line does, else the Friend's.
fn quota_secs_left(&self, now: Instant) -> Option<u64> {
let (progress, until) = if self.busy() {
(self.progress?, self.import_view.own_until?)
} else {
(
self.friends.import_progress()?,
self.import_view.friend_until?,
)
};
progress.quota_wait?;
let left = until.checked_duration_since(now).filter(|d| !d.is_zero())?;
Some(left.as_millis().div_ceil(1000) as u64)
}
/// After a message of an import or a change of the Account shown: starts the countdown if a
/// wait is on, and gives the ring what it shows.
pub(super) fn show_import(&mut self, force: bool, cx: &mut Context<Self>) {
self.count_down(cx);
self.show_arc(force, cx);
}
/// One timer for the whole wait: it draws the status line again each second and ends with it.
fn count_down(&mut self, cx: &mut Context<Self>) {
if self
.quota_secs_left(cx.background_executor().now())
.is_none()
{
self.import_view.counting = None;
return;
}
if self.import_view.counting.is_some() {
return;
}
self.import_view.counting = Some(cx.spawn(async move |page, cx| {
loop {
cx.background_executor().timer(EVERY).await;
let more = page.update(cx, |page, cx| {
cx.notify();
page.show_arc(false, cx);
let more = page
.quota_secs_left(cx.background_executor().now())
.is_some();
if !more {
page.import_view.counting = None;
}
more
});
if !more.unwrap_or(false) {
return;
}
}
}));
}
/// (fetched, to fetch) of the import of the Account shown, once it is long enough to show.
fn arc_wanted(&mut self) -> Option<(usize, usize)> {
let own = self.progress.filter(|p| p.to_fetch >= ARC_FROM);
if own.is_some() {
self.resolve_signed_in();
}
let shown = self.displayed()?.puuid.as_str();
let friend = (self.friends.import_running() == Some(shown))
.then(|| self.friends.import_progress())
.flatten();
let progress = friend.or_else(|| {
// The Account the follower or the refresh imports is the one signed in to the client;
// one not read yet shows no arc, rather than the previous Account's.
let imported = match &self.import_view.signed_in {
Some((_, puuid)) => puuid.as_deref(),
None => self.active_account().map(|a| a.puuid.as_str()),
};
(imported? == shown).then_some(own?)
})?;
(progress.to_fetch >= ARC_FROM).then_some((progress.fetched, progress.to_fetch))
}
/// Resolves the Account of the signed-in Riot ID when it changes, so an own import builds no
/// Riot ID per Account at each message (see `phase_account`).
fn resolve_signed_in(&mut self) {
let Some(id) = self.tracker.signed_in_riot_id_folded() else {
self.import_view.signed_in = None;
return;
};
if self
.import_view
.signed_in
.as_ref()
.is_none_or(|(known, _)| *known != id)
{
let named = (self.accounts.iter()).find(|a| account_riot_id(a).to_lowercase() == *id);
self.import_view.signed_in = Some((id, named.map(|a| a.puuid.clone())));
}
}
/// Gives the ring the arc: at once when it appears, disappears or `force`, else at most once
/// a second.
fn show_arc(&mut self, force: bool, cx: &mut Context<Self>) {
let wanted = self.arc_wanted();
let now = cx.background_executor().now();
let view = &mut self.import_view;
let toggled = wanted.is_some() != view.arc.is_some();
let due = view.arc_at.is_none_or(|at| now.duration_since(at) >= EVERY);
if wanted == view.arc || !(force || toggled || due) {
return;
}
view.arc = wanted;
view.arc_at = Some(now);
self.ring
.update(cx, |ring, cx| ring.set_progress(wanted, 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")
})),
)
}
+46
View File
@@ -0,0 +1,46 @@
use super::Page;
use crate::worker::spawn_refresh;
use gpui_kit::*;
impl Page {
/// The page gives way to another screen (« Paramètres »): what it shows is given back, the
/// grids' and the table's portraits and the banner's splash, in memory and in the window's
/// atlas. They load again when it is drawn.
pub(crate) fn hidden(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.covered = true;
self.end_stage(cx);
self.lifts.clear();
self.end_fade(window, cx);
for grid in [&self.home_grid, &self.anvil_grid, &self.others_grid] {
grid.update(cx, |grid, cx| grid.release_images(window, cx));
}
self.banner_art
.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 ».
pub(crate) fn uncovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.covered = false;
self.play_waiting(window, cx);
self.start_entry(window, cx);
}
/// 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());
}
cx.notify();
}
pub(crate) fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
}
+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();
});
}
}
}
+164
View File
@@ -0,0 +1,164 @@
//! The end of a Match opens its recap (#129): when its end-of-game block arrives, « Parties »
//! shows the new Match, from any screen; the window comes forward without 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, MatchEndShown, Page, 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);
cx.emit(MatchEndShown);
}
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);
cx.emit(MatchEndShown);
}
}
/// 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(MatchEndShown);
}
/// 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())
}
+356
View File
@@ -0,0 +1,356 @@
//! 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 {
// The Match chosen for the player, as one they click, shows their row.
self.request_recap(true);
}
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();
}
}
+105
View File
@@ -0,0 +1,105 @@
use super::{MatchPlayback, Page, Tab, WaitingMatch};
use crate::motion::MatchAnimation;
use arena_tracker_core::FollowedMatch;
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// Ends the end of a followed Match, waiting or playing: the banner shows its splash again,
/// and the champion's card leaves the grid if the filter or the search leave it out.
pub(in crate::page) fn end_match(&mut self, cx: &mut Context<Self>) {
// A Match the ring had no tick for left only its kept card.
let active = self.playback.active() || self.playback.kept_card.is_some();
self.playback = MatchPlayback::default();
if active {
self.dress_banner(cx);
self.refresh_home(cx);
}
}
/// 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>) {
if cx.reduce_motion() {
return;
}
if self.playback.animation.is_some() {
self.end_match(cx);
}
if self.playback.waiting.waiting().is_none() {
self.playback.previous_banner = Some(self.banner.clone());
}
self.playback.stats_pending = true;
let waiting = WaitingMatch {
end: event.end,
started_at_ms: event.started_at_ms,
champion_id: event.champion_id,
};
self.playback.waiting.request(waiting, false);
if self.playback.waiting.waiting() == Some(&waiting) {
let grid = self.home_grid.read(cx);
let card = (grid.cards().iter()).position(|c| c.id == event.champion_id);
self.playback.previous_card = card.map(|ix| Rc::new(grid.cards()[ix].clone()));
self.playback.kept_card = card
.filter(|ix| grid.shown().contains(ix))
.map(|_| event.champion_id);
}
}
/// 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 == screen
&& self.shown_tab == screen
&& self.fade.is_none()
&& !self.in_champ_select()
}
/// 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>) {
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()
{
#[cfg(test)]
self.played.push(waiting.end);
self.playback.animation = self.ring.read(cx).animation(
waiting.champion_id,
waiting.end,
cx.background_executor().now(),
);
// 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() {
// The ring has no tick for it: nothing plays.
self.end_match(cx);
}
cx.notify();
}
}
}
+27
View File
@@ -0,0 +1,27 @@
//! Measurement aid for issue #27: page parts hidden with `--features profile`.
/// Hides page parts for issue #27 measurements only with `--features profile`.
#[inline]
pub(in crate::page) fn shown(part: &str) -> bool {
#[cfg(feature = "profile")]
{
static HIDDEN: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
!HIDDEN
.get_or_init(|| {
std::env::var("ARENA_TRACKER_HIDE")
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.map(str::to_owned)
.collect()
})
.iter()
.any(|hidden| hidden == part)
}
#[cfg(not(feature = "profile"))]
{
let _ = part;
true
}
}
+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,
})
}
}
+21
View File
@@ -0,0 +1,21 @@
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::*;
/// The scrollbar of the champ select's scrolling, in the lane on the right of its column. It is
/// its own view for the scrollbar's fade: the frames it asks for are drawn for this view, not the
/// whole page.
pub(in crate::page) struct PageScrollbar {
pub(in crate::page) scroll: ScrollHandle,
}
impl Render for PageScrollbar {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(Scrollbar::width())
.child(Scrollbar::vertical(&self.scroll))
}
}
+305
View File
@@ -0,0 +1,305 @@
use super::friends::Friends;
use super::scrollbar::PageScrollbar;
use super::statistics::ChartsRow;
use super::{
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};
use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::AnimationSetting;
use crate::ring::Ring;
use crate::worker::{Msg, RefreshGate};
use arena_tracker_core::{ChampionSearch, SeasonScope, StateFilter, Tracker};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::IndexPath;
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::component::select::{SelectEvent, SelectState};
use gpui_kit::*;
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;
impl Page {
pub(crate) fn new(
tracker: Arc<Tracker>,
launch: Launch,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let Launch {
notice,
champion_sort,
open_recap_at_match_end,
} = launch;
let season_table = tracker.seasons();
let seasons: Vec<SharedString> = season_table
.iter()
.rev()
.map(|s| s.name.clone().into())
.chain([ALL_SEASONS.into()])
.collect();
let current_season = tracker.current_season(now_ms()).map(|s| s.name);
let season = current_season
.clone()
.map_or(SeasonScope::AllSeasons, SeasonScope::Season);
let selected = match &season {
SeasonScope::Season(name) => seasons.iter().position(|s| s.as_ref() == name.as_str()),
SeasonScope::AllSeasons => Some(seasons.len() - 1),
};
let account_select =
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)];
let format_select = cx
.new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx));
let sorts: Vec<SharedString> = SORTS.iter().map(|(_, label)| (*label).into()).collect();
let chosen = SORTS
.iter()
.position(|(sort, _)| Some(*sort) == champion_sort)
.unwrap_or(0);
let sort_select =
cx.new(|cx| SelectState::new(sorts, Some(IndexPath::new(chosen)), window, cx));
let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let charts = cx.new(|_| ChartsRow::new());
let home_search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let table = cx.new(|_| ChampionTable::new());
let home_grid = cx.new(|_| CardGrid::new());
let anvil_grid = cx.new(|_| CardGrid::fit_content());
let others_search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let paging = Paging {
scroll: ScrollHandle::new(),
top: Rc::new(Cell::new(None)),
};
let champ_select_scrollbar = cx.new(|_| PageScrollbar {
scroll: paging.scroll.clone(),
});
let others_grid = cx.new(|_| CardGrid::paged(paging.clone()));
let others_focus = cx.focus_handle().tab_stop(true);
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| {
if cx.reduce_motion() {
this.end_match(cx);
this.entry_waiting = false;
this.end_stage(cx);
this.lifts.finish(cx.background_executor().now());
this.end_fade(window, cx);
}
}),
// Minimised or hidden in the notification area, the window draws nothing: a
// transition ends at once, and an animation waits for it to show again.
cx.observe_window_visibility(window, |this, visibility, window, cx| {
if visibility.is_visible() {
this.play_waiting(window, cx);
this.start_entry(window, cx);
} else {
this.end_stage(cx);
this.lifts.finish(cx.background_executor().now());
this.end_fade(window, cx);
}
}),
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.search = ChampionSearch::new(&input.read(cx).value());
this.refresh_table(cx);
}
}),
cx.subscribe(&home_search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.home_search = ChampionSearch::new(&input.read(cx).value());
this.home_filtered(cx);
}
}),
cx.subscribe(
&others_search_input,
|this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.others_search = ChampionSearch::new(&input.read(cx).value());
this.refresh_others(cx);
}
},
),
cx.subscribe_in(
&account_select,
window,
|this, _, event: &SelectEvent<AccountList>, window, cx| {
if let SelectEvent::Confirm(Some(puuid)) = event {
this.account_chosen(puuid, window, cx);
}
},
),
cx.subscribe_in(
&season_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
this.season = if name.as_ref() == ALL_SEASONS {
SeasonScope::AllSeasons
} else {
SeasonScope::Season(name.to_string())
};
this.recompute(window, cx);
},
),
cx.subscribe(
&sort_select,
|this, _, event: &SelectEvent<Vec<SharedString>>, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
if let Some((sort, _)) = SORTS.iter().find(|(_, label)| *label == name.as_ref())
{
this.choose_sort(*sort, cx);
}
},
),
cx.subscribe_in(
&format_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
let formats = this.stats.iter().flat_map(|s| s.formats.iter());
this.format = formats.copied().find(|f| f.name() == name.as_ref());
this.recompute(window, cx);
},
),
]);
// gpui-kit's async channel wakes the page on sends, with no timer or extra dependency.
let listener = cx.spawn_in(window, async move |this, cx| {
while let Ok(msg) = rx.recv().await {
let applied = cx
.update(|window, app| this.update(app, |page, cx| page.apply(msg, window, cx)));
// The window or the page is gone: nothing left to update.
if !matches!(applied, Ok(Ok(()))) {
return;
}
}
});
let mut page = Page {
status: tracker.status(),
tracker,
tx,
notice,
champ_select: 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,
shown: None,
progress: None,
import_view: Default::default(),
refresh: RefreshGate::default(),
stats_job: RefreshGate::default(),
stats_generation: 0,
// The follower starts with the page: its first round is pending.
pending_round: true,
crashed: false,
last_reload: Instant::now(),
current_season,
tab: Tab::Challenge,
shown_tab: Tab::Challenge,
fade: None,
frame_asked: false,
lifts: Lifts::new(),
lifted_by_keyboard: None,
covered: false,
playback: MatchPlayback::default(),
hold_grid: false,
next_home: None,
entry: None,
entry_waiting: false,
leave: None,
taken: Vec::new(),
hover_waiting: None,
stage_frame_asked: false,
#[cfg(test)]
played: Vec::new(),
season,
format: None,
filter: StateFilter::All,
search: ChampionSearch::new(""),
search_input,
stats: None,
stats_error: None,
home_season: None,
home_scope: None,
home_stats: None,
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(""),
home_search_input,
champion_sort,
sort_select,
order: Vec::new(),
#[cfg(test)]
reorders: 0,
stored: None,
account_select,
account_items: Vec::new(),
friends,
season_select,
format_select,
format_names,
charts,
table,
home_grid,
home_cards_stale: false,
home_shown_count: SharedString::default(),
anvil_grid,
anvil_count: SharedString::default(),
others_open: false,
others_search: ChampionSearch::new(""),
others_search_input,
others_grid,
paging,
champ_select_scrollbar,
others_focus,
matches,
open_recap_at_match_end,
decided_game: None,
others_hover,
_subscriptions: subscriptions,
_listener: listener,
};
page.reload(window, cx);
page
}
}
+386
View File
@@ -0,0 +1,386 @@
//! The « Statistiques » page, the Challenge's detail: the analysis of one Account, Season and
//! Format.
mod data;
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;
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
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";
/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves
/// each chart 150 px: change them together.
const CHARTS_HEIGHT: f32 = 206.;
/// The state filters on offer: the Challenge ones only make sense in a Season.
fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] {
const SEASON: [(&str, StateFilter); 4] = [
("Tous", StateFilter::All),
("Validés", StateFilter::Completed),
("Restants", StateFilter::Remaining),
("Jamais joués", StateFilter::NeverPlayed),
];
if in_season {
&SEASON
} else {
&[SEASON[0], SEASON[3]]
}
}
fn tile(label: &'static str, value: String, theme: &Theme) -> impl IntoElement {
div()
.debug_selector(move || format!("tile-{label}"))
.v_flex()
.flex_1()
.gap_1()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(label),
)
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
}
fn challenge_tiles(c: &ChallengeSummary, theme: &Theme) -> impl IntoElement {
let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2));
div()
.h_flex()
.gap_3()
.child(tile(
"Champions validés",
format!("{} / {}", c.completed, c.total),
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.
fn card(
title: Div,
chart: Option<AnyElement>,
empty: &'static str,
theme: &Theme,
) -> impl IntoElement {
let body = chart.unwrap_or_else(|| {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(theme.muted_foreground)
.child(empty)
.into_any_element()
});
div()
.v_flex()
.flex_1()
.min_w_0()
.h_full()
.gap_2()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(title.text_sm())
.child(div().flex_1().min_h_0().w_full().children(Some(body)))
}
/// The charts, a cached view: hovering the table, which redraws the page, does not draw them
/// again (#31). The page updates it from `show_statistics`.
pub(in crate::page) struct ChartsRow {
/// Empty when there are no statistics.
charts: Charts,
in_season: bool,
/// Guards the cache in tests.
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl ChartsRow {
pub(in crate::page) fn new() -> ChartsRow {
ChartsRow {
charts: Charts {
placements: vec![],
completed_over_time: vec![],
attempts_to_complete: [0; 5],
},
in_season: false,
#[cfg(test)]
renders: 0,
}
}
/// Shows `charts`, or none; drawing them again only when they changed, since reloads keep
/// coming during an import.
pub(in crate::page) fn set(
&mut self,
charts: Option<&Charts>,
in_season: bool,
cx: &mut Context<Self>,
) {
let charts = charts.cloned().unwrap_or_else(|| ChartsRow::new().charts);
if (&self.charts, self.in_season) != (&charts, in_season) {
self.charts = charts;
self.in_season = in_season;
cx.notify();
}
}
}
impl Render for ChartsRow {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let theme = cx.theme();
let charts = &self.charts;
let mut cards = Vec::new();
// The curve first: it is the Season's story, the others detail it.
if self.in_season {
cards.push(
card(
heading(cx).child("Champions validés au fil de la Saison"),
if shown("completed") {
completed_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
theme,
)
.into_any_element(),
);
}
cards.push(
card(
heading(cx).child("Répartition des Placements"),
if shown("placements") {
placements_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
NO_MATCH,
theme,
)
.into_any_element(),
);
if self.in_season {
cards.push(
card(
heading(cx).child("Tentatives pour valider"),
if shown("attempts") {
attempts_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
theme,
)
.into_any_element(),
);
}
div().h_flex().size_full().gap_3().children(cards)
}
}
fn placements_chart(charts: &Charts) -> Option<AnyElement> {
(!charts.placements.is_empty()).then(|| {
BarChart::new(charts.placements.clone())
.id("placements")
.band(|(placement, _)| placement.to_string())
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Parties")
.into_any_element()
})
}
fn completed_chart(charts: &Charts) -> Option<AnyElement> {
let points: Vec<(String, f64)> = charts
.completed_over_time
.iter()
.map(|(day, count)| (day.to_string(), *count as f64))
.collect();
// The counts only grow, so the last one is the highest. The y axis runs from 0 to a
// multiple of 4 in four steps with no padding: every tick is then a whole number.
let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n);
let top = top.div_ceil(4).max(1) * 4;
(!points.is_empty()).then(|| {
AreaChart::new(points)
.id("completed")
.x(|(day, _)| day.clone())
.y(|(_, count)| *count)
.linear()
.x_tick_count(3)
.y_axis(true)
.y_domain(0., top as f64)
.y_padding(0., 0.)
.y_tick_count(5)
.name("Champions validés")
.into_any_element()
})
}
fn attempts_chart(charts: &Charts) -> Option<AnyElement> {
const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"];
let bars: Vec<(&str, usize)> = LABELS
.into_iter()
.zip(charts.attempts_to_complete)
.collect();
bars.iter().any(|(_, count)| *count > 0).then(|| {
BarChart::new(bars)
.id("attempts")
.band(|(label, _)| *label)
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Champions")
.into_any_element()
})
}
impl Page {
/// The Season and Format selectors, which only the statistics have.
fn statistics_selectors(&self) -> [AnyElement; 2] {
[
Select::new(&self.season_select)
.id("season")
.w(px(220.))
.min_w(px(130.))
.into_any_element(),
Select::new(&self.format_select)
.id("format")
.w(px(220.))
.min_w(px(130.))
.into_any_element(),
]
}
/// Under the banners: the Challenge tiles, the charts, the filters and the table.
pub(in crate::page) fn statistics_content(&self, cx: &mut Context<Page>) -> Vec<AnyElement> {
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.
content.push(
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_3()
.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()
.items_center()
.gap_3()
.min_w_0()
.children(self.statistics_selectors()),
)
.into_any_element(),
);
if shown("tiles")
&& let Some(c) = challenge
{
content.push(challenge_tiles(c, cx.theme()).into_any_element());
}
content.push(
self.charts
.clone()
.cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT)))
.into_any_element(),
);
if shown("tabs") {
content.push(
div()
.h_flex()
.items_center()
.justify_between()
.gap_3()
.child(
TabBar::new("state-filter")
.pill()
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = filters(this.in_season()).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
}
})),
)
.child(
input_frame(
&self.search_input,
Input::new(&self.search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.)),
)
.into_any_element(),
);
}
if shown("table") {
content.push(
div()
.flex_1()
.min_h(px(240.))
// A cached view, laid out by the space the page gives it: the veil of a
// transition, which draws the page again at each frame, does not draw it.
.child(
self.table
.clone()
.cached(StyleRefinement::default().size_full()),
)
.into_any_element(),
);
}
content
}
}
+272
View File
@@ -0,0 +1,272 @@
use crate::card::Card;
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::{Scope, SeasonScope, StateFilter};
use gpui_kit::component::IndexPath;
use gpui_kit::*;
use std::time::Instant;
impl Page {
/// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
/// visible nor a hidden window waits for them (rule #1).
pub(in crate::page) fn reload_in_background(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.reload_accounts(window, cx);
let start_job = self.stats_job.request();
self.recompute_in_background(start_job, window, cx);
}
/// Re-reads the Accounts, then the statistics of the one shown.
pub(in crate::page) fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reload_accounts(window, cx);
self.recompute(window, cx);
}
/// Re-reads the Accounts and selects the one shown.
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);
self.follow_replaced_puuids();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
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.phase_riot_id = None;
self.import_view.signed_in = None;
}
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 let Some(puuid) = &shown
&& select.selected_value() != Some(puuid)
{
select.set_selected_value(puuid, window, cx);
}
});
}
/// Settles the scope of the next statistics. Earlier results become stale when they are
/// computed again (`computing`) or when the viewed Account changed; a request merely queued
/// behind a running job keeps that job's result for the same scope.
fn prepare_statistics(
&mut self,
computing: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
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());
if previous_season != self.home_season || viewed != self.shown {
self.stop_holding();
self.end_match(cx);
}
if computing || viewed != self.shown {
self.stats_generation += 1;
}
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| {
select.set_selected_index(Some(IndexPath::new(0)), window, cx)
});
}
}
viewed
}
/// Requests the statistics from a worker (`start_job`: none is running), or shows none when no
/// Account is viewed.
pub(in crate::page) fn recompute_in_background(
&mut self,
start_job: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let viewed = self.prepare_statistics(start_job, window, cx);
if let Some(puuid) = viewed {
if start_job {
let scope = self.statistics_scope();
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
puuid,
scope,
self.home_scope.clone(),
self.stats_generation,
self.tx.clone(),
);
}
} else {
if start_job {
self.stats_job.reset();
}
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.show_statistics(window, cx);
}
}
/// Recomputes the statistics for the current scope; never called while rendering. The home's
/// own statistics are kept when they were computed for the same Account and scope (a change
/// of Format leaves them as they are).
pub(in crate::page) fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let viewed = self.prepare_statistics(true, window, cx);
self.stats = None;
self.stats_error = None;
self.stored = None;
let keep_home = !self.playback.stats_pending && viewed.is_some() && self.home_is_current();
if !keep_home {
self.forget_home();
}
if let Some(puuid) = &viewed {
let scope = self.statistics_scope();
match compute_statistics(&self.tracker, puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(error) => self.stats_error = Some(error),
}
if !keep_home {
let home = (self.home_scope.clone())
.map(|home| Box::new(compute_statistics(&self.tracker, puuid, &home)));
self.set_home_result(home);
}
self.stored = self.tracker.match_count(puuid).ok();
}
self.show_statistics(window, cx);
}
/// Shows `stats`: the Format choices, the charts and the table.
pub(in crate::page) fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.hold_grid {
// Row indices are reusable only while the catalog has the same champions.
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let cards = self.home_grid.read(cx).cards();
let same = rows.len() == cards.len()
&& self.order.len() == rows.len()
&& self
.order
.iter()
.zip(cards.iter())
.all(|(&ix, c)| rows.get(ix).is_some_and(|r| r.champion.id == c.id));
if !same || self.in_champ_select() {
self.stop_holding();
}
}
if !self.hold_grid {
self.reorder();
}
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();
self.charts
.update(cx, |row, cx| row.set(charts, in_season, cx));
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
.iter()
.flat_map(|s| s.formats.iter().map(|f| SharedString::from(f.name()))),
);
if names != self.format_names {
self.format_names = names.clone();
self.format_select
.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.
let order = self.sorted_order();
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let cards = order
.iter()
.filter_map(|&ix| rows.get(ix))
.map(Card::from_row)
.collect();
let shown = self.home_shown(&order);
self.next_home = Some(NextHome {
count: shown.len().to_string().into(),
order,
cards,
shown,
});
} else {
self.refresh_home(cx);
}
self.playback.stats_pending = false;
self.play_waiting(window, cx);
cx.notify();
}
}
+47
View File
@@ -0,0 +1,47 @@
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;
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 import_arc;
mod import_quota;
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;
pub(crate) mod page_fixtures;
mod portraits;
mod ring_hover;
mod sorting;
mod sorting_fixtures;
mod statistics_tiles;
+246
View File
@@ -0,0 +1,246 @@
use super::champ_select_fixtures::finish_motion;
use super::page_fixtures::{
RefreshHistory, open_page, open_page_with_tracker, refresh_towards_bob, switch_tab,
};
use crate::champion_table::tests::row;
use crate::page::Tab;
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Charts, Format, StateFilter, Statistics, Tracker,
};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, point, px};
use std::cell::{Cell, RefCell};
use std::path::Path;
use std::rc::Rc;
#[gpui::test]
async fn a_refresh_keeps_following_the_account_being_updated(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, false).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned, None);
assert_eq!(page.viewed().unwrap().puuid, "Bob");
// Another Account may not have played the Format: the filter is dropped
// (`prepare_statistics`), whatever the refresh.
assert_eq!(page.format, None);
});
}
#[gpui::test]
async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, true).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned.as_deref(), Some("Alice"));
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.format, Some(Format::Arena3x6));
});
}
#[gpui::test]
async fn champ_select_uses_the_signed_in_accounts_challenge_and_leaves_the_active_account_shown(
cx: &mut TestAppContext,
) {
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, SeasonScope};
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {});
let (page, mut window) = open_page_with_tracker(cx, tracker);
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Bob".into());
p.season = SeasonScope::AllSeasons;
p.filter = StateFilter::NeverPlayed;
p.reload(w, cx);
assert!(p.stats.as_ref().unwrap().rows.is_empty());
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
// « 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());
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
// A hover change touches neither the Account nor the pool: the card follows it.
let next = ChampSelect::new(None, [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), next))), w, cx);
})
});
page.read_with(cx, |p, cx| {
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
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, _| {
// 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::All);
assert_eq!(p.tab, Tab::Challenge);
});
}
#[gpui::test]
fn only_entering_a_champ_select_is_reported_as_an_entry(cx: &mut TestAppContext) {
use crate::worker::Msg;
use arena_tracker_core::ChampSelect;
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &crate::page::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
let hovered = |current| ChampSelect::new(current, [39].into(), Some(vec![39]));
for champ_select in [
None,
Some(("Alice#EUW".into(), hovered(Some(39)))),
Some(("Alice#EUW".into(), hovered(None))),
None,
None,
] {
window.update(|w, cx| {
page.update(cx, |p, cx| p.apply(Msg::ChampSelect(champ_select), w, cx))
});
}
// The champ select ends once its hand has left.
finish_motion(&page, &mut window);
assert_eq!(*entered.borrow(), [true, false]);
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
..row(name)
};
page.update(cx, |page, _| {
page.stats = Some(Statistics {
challenge: None,
rows: vec![
ChampionRow {
state: Some(ChampionState::Completed),
..champion(4, "TwistedFate", "Twisted Fate")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
..champion(86, "Garen", "Garen")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
matches: 5,
..champion(107, "Rengar", "Rengar")
},
],
charts: Charts {
placements: Vec::new(),
completed_over_time: Vec::new(),
attempts_to_complete: [0; 5],
},
formats: Vec::new(),
});
});
// The search field of the Statistics tab is only there on that tab.
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
let (input, table) = page.read_with(cx, |p, _| (p.search_input.clone(), p.table.clone()));
let names = |cx: &mut VisualTestContext| table.read_with(cx, |table, _| table.names());
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("ren");
assert_eq!(names(cx), ["Rengar", "Garen"]);
// The clear button's own path: it empties the field and the table follows.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(names(cx).len(), 3);
cx.simulate_input("TF");
assert_eq!(names(cx), ["Twisted Fate"]);
cx.simulate_input("z");
assert!(names(cx).is_empty());
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input(" ");
assert_eq!(names(cx).len(), 3);
// Combined with a state filter, the table keeps its sort (most Matches first).
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input("ren");
page.update(cx, |page, cx| {
page.filter = StateFilter::Completed;
page.refresh_table(cx);
});
assert!(names(cx).is_empty());
page.update(cx, |page, cx| {
page.filter = StateFilter::NeverPlayed;
page.refresh_table(cx);
});
assert_eq!(names(cx), ["Rengar", "Garen"]);
}
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
// The table hovered is the Statistics tab's: the app opens on the Challenge.
switch_tab(&page, cx, Tab::Statistics);
let (table, charts) = page.read_with(cx, |page, _| (page.table.clone(), page.charts.clone()));
// Enough rows to fill the table, under the points hovered below.
table.update(cx, |table, cx| {
let rows = (1..=20).map(|n| row(&format!("Champion {n}")));
table.set_rows(rows.collect(), false);
cx.notify();
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let renders = charts.read_with(cx, |charts, _| charts.renders);
assert!(renders > 0);
// A row's hover style notifies the table, which redraws the page.
let hovers = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let hovers = hovers.clone();
cx.observe(&table, move |_, _| hovers.set(hovers.get() + 1))
});
for y in [700., 740.] {
cx.simulate_mouse_move(point(px(300.), px(y)), None, Modifiers::none());
cx.update(|window, cx| window.draw(cx).clear(cx));
}
assert!(hovers.get() > 0, "no row was hovered");
assert_eq!(charts.read_with(cx, |charts, _| charts.renders), renders);
// The count does move when the charts change.
charts.update(cx, |_, cx| cx.notify());
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(
charts.read_with(cx, |charts, _| charts.renders),
renders + 1
);
}
@@ -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);
})
});
}
+500
View File
@@ -0,0 +1,500 @@
use super::banner_fixtures::{
banner, banner_champion, banner_rows, banner_statistics, bold, draw_loaded, held_splashes,
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,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::page::Tab;
use arena_tracker_core::{
ChampionChallenge, ChampionRow, ChampionSort, ChampionState, LastMatch, MatchOutcome,
StateFilter,
};
use gpui_kit::{
Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px, size,
};
use std::cell::Cell;
use std::rc::Rc;
#[gpui::test]
fn the_banner_says_the_count_the_last_completion_and_the_last_match(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let last_match = |champion_id, placement, outcome| {
Some(LastMatch {
champion_id,
placement,
outcome,
})
};
let cases = [
// Not yet Completed: its Attempt, the first one feminine.
(
last_match(3, 4, MatchOutcome::Attempt(3)),
"Dernière Partie : Zyra, 4ᵉ · 3ᵉ Tentative",
),
(
last_match(3, 2, MatchOutcome::Attempt(1)),
"Dernière Partie : Zyra, 2ᵉ · 1ʳᵉ Tentative",
),
// The Match that completes it.
(
last_match(1, 1, MatchOutcome::Completed(3)),
"Dernière Partie : Ahri, 1ᵉʳ · validé en 3 Tentatives",
),
(
last_match(1, 1, MatchOutcome::Completed(1)),
"Dernière Partie : Ahri, 1ᵉʳ · validé du premier coup",
),
// Already Completed.
(
last_match(2, 4, MatchOutcome::AfterCompletion),
"Dernière Partie : Brand, 4ᵉ",
),
];
for (last, expected) in cases {
show(
&page,
cx,
banner_statistics(banner_rows(), vec![2, 1], last),
);
draw(cx);
let text = banner(&page, cx);
assert_eq!(text.season.as_ref(), "SAISON");
assert_eq!(text.title.text.as_ref(), "2 / 5 champions validés");
assert_eq!(bold(&text.title), "2");
assert_eq!(
text.detail.text.as_ref(),
"Dernier champion validé : Ahri, le 20 nov."
);
assert_eq!(bold(&text.detail), "Ahri");
let line = text.last_match.expect("no last Match line");
assert_eq!(line.text.as_ref(), expected);
let champion = expected["Dernière Partie : ".len()..].split(',').next();
assert_eq!(Some(bold(&line)), champion);
assert!(cx.debug_bounds("banner-title").is_some());
}
// A Season without a Completed champion nor a Match.
let never: Vec<_> = banner_rows()
.into_iter()
.map(|row| ChampionRow {
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
..row
})
.collect();
show(&page, cx, banner_statistics(never, Vec::new(), None));
draw(cx);
let text = banner(&page, cx);
assert_eq!(text.title.text.as_ref(), "0 / 5 champions validés");
assert_eq!(
text.detail.text.as_ref(),
"Aucun champion validé pour l’instant."
);
assert_eq!(text.last_match, None);
assert_eq!(text.splash, None);
assert!(cx.debug_bounds("banner-title").is_some());
assert!(cx.debug_bounds("banner-art").is_none());
}
#[gpui::test]
fn the_ring_keeps_its_fixed_order_whatever_the_sort(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(banner_rows(), vec![2, 1], None),
);
draw(cx);
let expected = [
(2, ChampionState::Completed),
(1, ChampionState::Completed),
(4, ChampionState::InProgress),
(3, ChampionState::InProgress),
(5, ChampionState::NeverPlayed),
];
assert_eq!(ring_ticks(&page, cx), expected);
assert!(cx.debug_bounds("ring").is_some());
let renders = ring_renders(&page, cx);
// The cards follow the sort; the ring does not, and is not drawn again.
page.update(cx, |page, cx| page.choose_sort(ChampionSort::Name, cx));
draw(cx);
assert_eq!(ring_ticks(&page, cx), expected);
assert_eq!(ring_renders(&page, cx), renders);
}
// The ring is a cached view (rule #1): hovering the grid draws it again only when a tick
// lights up or goes out, and builds no card.
#[gpui::test]
fn hovering_the_grid_draws_the_ring_only_for_the_tick_that_lights_or_goes_out(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = ring_renders(&page, cx);
assert!(renders > 0);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let hover = |cx: &mut VisualTestContext, at: gpui_kit::Point<gpui_kit::Pixels>| {
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
};
let card = cx.debug_bounds("card-1").unwrap();
hover(cx, card.center());
assert_eq!(lit(cx), Some(1));
assert_eq!(ring_renders(&page, cx), renders + 1);
// Elsewhere on the same card: nothing changes.
hover(cx, card.center() + point(px(10.), px(10.)));
assert_eq!(ring_renders(&page, cx), renders + 1);
let at = center(cx, "card-2");
hover(cx, at);
assert_eq!(lit(cx), Some(2));
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, "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, "statistics-link");
hover(cx, at);
assert_eq!(ring_renders(&page, cx), renders + 3);
// Scrolling moves the cards under a still pointer: the ring is drawn again only when
// that changes the lit tick, at most once a frame.
let at = center(cx, "card-1");
hover(cx, at);
assert_eq!(ring_renders(&page, cx), renders + 4);
// The grid tells each change of the card under the pointer, and only a change.
let changes = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let changes = changes.clone();
cx.subscribe(&grid, move |_, _: &crate::card_grid::CardHovered, _| {
changes.set(changes.get() + 1)
})
});
for _ in 0..3 {
let (was_changed, was_drawn) = (changes.get(), ring_renders(&page, cx));
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(-200.))),
..Default::default()
});
draw(cx);
assert_eq!(
ring_renders(&page, cx) - was_drawn,
changes.get() - was_changed
);
}
assert!(
changes.get() > 0,
"no scroll changed the card under the pointer"
);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
// A grid that is no longer shown has no card under the pointer.
hover(cx, point(px(5.), px(5.)));
hover(cx, at);
assert!(lit(cx).is_some());
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(lit(cx), None);
}
#[gpui::test]
fn the_banner_holds_two_splashes_at_most_and_gives_back_the_one_replaced(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-splashes");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
// Ahri was Completed last: its splash is the illustration.
show(
&page,
cx,
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());
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
let ahri = loaded_splashes(&page, cx);
assert_eq!(ahri.len(), 1, "the splash was not decoded");
assert!(in_atlas(cx, &ahri[0]));
// Never through the app-wide asset cache, which would keep it.
let source = gpui_kit::ImageSource::from(dir.path().join("Ahri.50.30.jpg"));
assert!(!cx.update(|_, cx| source.is_asset_cached(cx)));
// Brand is now the last: Ahri stays shown while Brand decodes, then is given back.
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![1, 2], last_match_of(2)),
);
draw(cx);
assert_eq!(
held_splashes(&page, cx),
["Ahri.50.30.jpg", "Brand.50.30.jpg"]
);
assert!(loaded_splashes(&page, cx).len() <= 2);
cx.run_until_parked();
draw(cx);
assert_eq!(loaded_splashes(&page, cx).len(), 2);
assert!(in_atlas(cx, &ahri[0]));
cx.update(|_, cx| {
cx.background_executor()
.advance_clock(std::time::Duration::from_millis(501))
});
draw(cx);
assert_eq!(held_splashes(&page, cx), ["Brand.50.30.jpg"]);
let brand = loaded_splashes(&page, cx);
assert_eq!(brand.len(), 1);
assert!(in_atlas(cx, &brand[0]));
assert!(!in_atlas(cx, &ahri[0]));
// « Statistiques » has no banner: its splash is given back, and comes back with it.
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
assert!(held_splashes(&page, cx).is_empty());
assert!(!in_atlas(cx, &brand[0]));
switch_tab(&page, cx, Tab::Challenge);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Brand.50.30.jpg"]);
}
#[gpui::test]
fn a_banner_without_splash_has_no_illustration(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-no-splash");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
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 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], last_match_of(1)),
);
draw(cx);
assert!(cx.debug_bounds("banner").is_some());
assert!(cx.debug_bounds("banner-title").is_some());
assert!(cx.debug_bounds("banner-art").is_none());
assert!(held_splashes(&page, cx).is_empty());
}
#[gpui::test]
fn in_a_narrow_window_the_ring_goes_above_the_text_and_the_splash_covers_the_banner(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("banner-narrow");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
draw(cx);
let bounds = |cx: &mut VisualTestContext| {
["banner", "ring", "banner-title", "banner-art"].map(|id| cx.debug_bounds(id).unwrap())
};
// Wide: the ring beside the text, the splash on the right.
let [banner, ring, title, art] = bounds(cx);
assert!(ring.right() <= title.left(), "{ring:?} {title:?}");
assert!((art.size.width.as_f32() - 0.72 * banner.size.width.as_f32()).abs() < 1.);
assert_eq!(art.right(), banner.right());
cx.simulate_resize(size(px(600.), px(860.)));
draw(cx);
let [banner, ring, title, art] = bounds(cx);
assert!(ring.bottom() <= title.top(), "{ring:?} {title:?}");
assert_eq!(art.size.width, banner.size.width);
assert_eq!(art.size.height, banner.size.height);
}
// Only the ring is invalidated: the grid is not drawn again, no card is built, and its fixed
// shapes are not tessellated again for a new lit tick.
#[gpui::test]
fn lighting_a_tick_draws_the_ring_alone_and_tessellates_only_that_tick(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let (ring, grid) = page.read_with(cx, |p, _| (p.ring.clone(), p.home_grid.clone()));
let grid_state = |cx: &mut VisualTestContext| {
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls)
})
};
let tessellations =
|cx: &mut VisualTestContext| ring.read_with(cx, |ring, _| ring.tessellations.get());
let before = grid_state(cx);
let shapes = tessellations(cx);
let renders = ring_renders(&page, cx);
for lit in [Some(5), Some(90), None] {
ring.update(cx, |ring, cx| ring.set_lit(lit, cx));
draw(cx);
}
assert_eq!(ring_renders(&page, cx), renders + 3);
assert_eq!(grid_state(cx), before);
assert_eq!(tessellations(cx), shapes);
// New ticks are tessellated once.
show(&page, cx, statistics(0, 171, champions(171)));
draw(cx);
assert_eq!(tessellations(cx), shapes + 1);
}
#[gpui::test]
fn a_splash_asked_for_while_another_decodes_waits_for_it(cx: &mut TestAppContext) {
cx.update(|cx| cx.set_reduce_motion(true));
let dir = TestDir::new("banner-queue");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
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>| {
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);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
// Brand starts decoding; Garen is asked for before it ends, and waits.
show(&page, cx, last(vec![1, 2]));
draw(cx);
show(&page, cx, last(vec![1, 2, 4]));
draw(cx);
assert_eq!(
held_splashes(&page, cx),
["Ahri.50.30.jpg", "Brand.50.30.jpg"]
);
cx.run_until_parked();
draw(cx);
assert_eq!(held_splashes(&page, cx), ["Garen.50.30.jpg"]);
assert!(!in_atlas(cx, &ahri[0]));
let loads = page.read_with(cx, |p, cx| p.banner_art.read(cx).loads);
assert_eq!(loads, 3);
}
#[gpui::test]
fn opening_another_screen_gives_back_the_splash_and_the_portraits(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-hidden");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = rows_with_splashes(dir.path());
for row in &mut rows {
let path = dir.path().join(format!("{}.card.jpg", row.champion.key));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
row.card_portrait = Some(path);
}
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());
let splash = loaded_splashes(&page, cx);
assert!(!portraits.is_empty() && splash.len() == 1);
// Checked before any frame: here the page is the window's root and would be drawn
// again, where the app shows « Paramètres » in its place.
let (held, portraits_held, in_atlas) = cx.update(|window, cx| {
page.update(cx, |page, cx| page.hidden(window, cx));
let held = page.read(cx).banner_art.read(cx).held();
let portraits_held = images.read(cx).held();
let in_atlas = (portraits.iter().chain(&splash))
.filter(|image| window.has_image_atlas_entry(image))
.count();
(held, portraits_held, in_atlas)
});
assert!(held.is_empty(), "{held:?}");
assert!(portraits_held.is_empty(), "{portraits_held:?}");
assert_eq!(in_atlas, 0);
}
#[gpui::test]
fn in_a_low_window_the_home_scrolls_to_its_grid(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 30, champions(30)));
cx.simulate_resize(size(px(600.), px(340.)));
draw(cx);
let visible = |cx: &mut VisualTestContext| {
cx.debug_bounds("card-1")
.is_some_and(|b| b.top() < px(340.))
};
assert!(!visible(cx));
let banner = center(cx, "banner");
cx.simulate_event(ScrollEvent {
position: banner,
delta: ScrollDelta::Pixels(point(px(0.), px(-2000.))),
..Default::default()
});
draw(cx);
assert!(visible(cx));
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(1));
}
#[gpui::test]
fn the_tick_follows_the_card_actually_under_the_pointer(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(lit(cx), Some(1));
// A wheel at the top of the list moves no card: the tick stays, the ring is not drawn.
let renders = ring_renders(&page, cx);
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(400.))),
..Default::default()
});
draw(cx);
assert_eq!(lit(cx), Some(1));
assert_eq!(ring_renders(&page, cx), renders);
// The card leaves the grid (« Validés » here): its tick goes out.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(lit(cx), None);
}
@@ -0,0 +1,155 @@
use super::page_fixtures::{draw, statistics};
use crate::card_images::tests::PORTRAIT_JPEG;
use crate::champion_table::tests::row;
use crate::page::Page;
use crate::ring::Tick;
use arena_tracker_core::{
Champion, ChampionChallenge, ChampionRow, ChampionState, Date, LastMatch, MatchOutcome, Splash,
SplashFocus, Statistics,
};
use gpui_kit::{Entity, VisualTestContext};
use std::path::Path;
use std::sync::Arc;
pub(super) fn on(month: u8, day: u8) -> Date {
Date {
year: 2026,
month,
day,
}
}
/// One champion of the banner's tests: `completed_on` makes it Completed, `matches` played.
pub(super) fn banner_champion(
id: u32,
name: &str,
matches: usize,
completed_on: Option<Date>,
points: u64,
) -> ChampionRow {
let state = match (completed_on, matches) {
(Some(_), _) => ChampionState::Completed,
(None, 0) => ChampionState::NeverPlayed,
(None, _) => ChampionState::InProgress,
};
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
state: Some(state),
challenge: Some(ChampionChallenge {
matches,
completed_on,
..Default::default()
}),
mastery_points: Some(points),
..row(name)
}
}
/// Brand then Ahri Completed, Garen and Zyra played, Lux never played; A to Z.
pub(super) fn banner_rows() -> Vec<ChampionRow> {
vec![
banner_champion(1, "Ahri", 3, Some(on(11, 20)), 100),
banner_champion(2, "Brand", 1, Some(on(11, 3)), 5),
banner_champion(4, "Garen", 2, None, 900),
banner_champion(5, "Lux", 0, None, 10),
banner_champion(3, "Zyra", 4, None, 50),
]
}
pub(super) fn banner_statistics(
rows: Vec<ChampionRow>,
completion_order: Vec<u32>,
last_match: Option<LastMatch>,
) -> Statistics {
let mut stats = statistics(completion_order.len(), rows.len(), rows);
let challenge = stats.challenge.as_mut().unwrap();
challenge.completion_order = completion_order;
challenge.last_match = last_match;
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.shown_banner().clone())
}
pub(super) fn bold(line: &crate::page::home::Line) -> &str {
&line.text[line.bold.clone()]
}
pub(super) fn ring_ticks(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<(u32, ChampionState)> {
page.read_with(cx, |page, cx| {
page.ring
.read(cx)
.ticks()
.iter()
.map(|tick: &Tick| (tick.id, tick.state))
.collect()
})
}
pub(super) fn ring_renders(page: &Entity<Page>, cx: &mut VisualTestContext) -> usize {
page.read_with(cx, |page, cx| page.ring.read(cx).renders)
}
pub(super) fn splash(dir: &Path, key: &str) -> Splash {
let path = dir.join(format!("{key}.50.30.jpg"));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
Splash {
path,
focus: SplashFocus { x: 50, y: 30 },
}
}
/// `banner_rows`, Ahri and Brand with a splash each.
pub(super) fn rows_with_splashes(dir: &Path) -> Vec<ChampionRow> {
let mut rows = banner_rows();
rows[0].splash = Some(splash(dir, "Ahri"));
rows[1].splash = Some(splash(dir, "Brand"));
rows
}
pub(super) fn draw_loaded(cx: &mut VisualTestContext) {
draw(cx);
cx.run_until_parked();
draw(cx);
}
pub(super) fn held_splashes(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<String> {
page.read_with(cx, |page, cx| {
let held = page.banner_art.read(cx).held();
held.iter()
.map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
.collect()
})
}
pub(super) fn loaded_splashes(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<Arc<gpui_kit::RenderImage>> {
page.read_with(cx, |page, cx| page.banner_art.read(cx).loaded())
}
pub(super) fn in_atlas(cx: &mut VisualTestContext, image: &gpui_kit::RenderImage) -> bool {
cx.update(|window, _| window.has_image_atlas_entry(image))
}
+79
View File
@@ -0,0 +1,79 @@
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("", "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);
}
+196
View File
@@ -0,0 +1,196 @@
use super::banner_fixtures::{
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,
send, with_bans_and_ally,
};
use super::page_fixtures::{center, draw, open_page_in_season, open_page_with_tracker, show};
use crate::card_images::tests::TestDir;
use gpui_kit::{
Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px, size,
};
#[gpui::test]
async fn the_banner_forgets_the_previous_scope_while_the_champ_select_loads(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("banner-scope");
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
cx.condition(&page, |p, _| p.stats.is_some()).await;
show(
&page,
&mut window,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], last_match_of(1)),
);
assert_eq!(
banner(&page, &mut window).title.text.as_ref(),
"2 / 5 champions validés"
);
send(&page, &mut window, &frames()[0]);
let text = banner(&page, &mut window);
assert_eq!(text.title.text.as_ref(), "Sélection des champions");
assert!(!text.season.contains('/'));
assert_eq!(text.splash, None);
assert!(ring_ticks(&page, &mut window).is_empty());
// Its own statistics arrive.
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert!(banner(&page, &mut window).season.contains("1 / 9"));
}
#[gpui::test]
fn scrolling_the_home_moves_the_ring_as_it_is_and_gives_back_a_splash_out_of_view(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("banner-scrolled");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
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);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
let splash = loaded_splashes(&page, cx);
let ring = page.read_with(cx, |p, _| p.ring.clone());
let tessellations =
|cx: &mut VisualTestContext| ring.read_with(cx, |ring, _| ring.tessellations.get());
let shapes = tessellations(cx);
let scroll = |cx: &mut VisualTestContext, by: f32| {
let at = center(cx, "banner");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(by))),
..Default::default()
});
draw(cx);
};
// The ring moves with the column, as it is.
let top = cx.debug_bounds("ring").unwrap().top();
scroll(cx, -30.);
assert!(cx.debug_bounds("ring").unwrap().top() < top);
assert_eq!(tessellations(cx), shapes);
// Down to the grid: the banner is out of view, and so is its splash, from the atlas too.
scroll(cx, -2000.);
assert!(held_splashes(&page, cx).is_empty());
assert!(!in_atlas(cx, &splash[0]));
// Back up: it comes back.
let at = center(cx, "card-1");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(4000.))),
..Default::default()
});
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
}
#[gpui::test]
async fn the_champ_select_splash_follows_the_hand_and_other_champions(cx: &mut TestAppContext) {
let dir = TestDir::new("champ-select-splashes");
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
let mut stats = page.read_with(cx, |p, _| p.home_statistics().unwrap().clone());
for row in &mut stats.rows {
row.splash = Some(splash(dir.path(), &row.champion.key));
}
show(&page, cx, stats);
cx.simulate_resize(size(px(1280.), px(1300.)));
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Briar.50.30.jpg"]);
click_others(cx);
let hover = |cx: &mut VisualTestContext, card| {
let at = center(cx, card);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw_loaded(cx);
};
let finish_fade = |cx: &mut VisualTestContext| {
cx.update(|_, cx| {
cx.background_executor()
.advance_clock(std::time::Duration::from_millis(501))
});
draw_loaded(cx);
};
// The first hover starts a fade. Crossing the rest of the hand leaves
// those two images intact until it ends, even over an Other champion.
for card in ANVIL_CARDS[1..].iter().copied().chain(["card-103"]) {
hover(cx, card);
assert_eq!(
held_splashes(&page, cx),
["Briar.50.30.jpg", "LeeSin.50.30.jpg"]
);
}
let builds = page.read_with(cx, |p, cx| p.anvil_grid.read(cx).card_builds);
finish_fade(cx);
assert_eq!(
held_splashes(&page, cx),
["LeeSin.50.30.jpg", "Ahri.50.30.jpg"]
);
finish_fade(cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
assert_eq!(
page.read_with(cx, |p, cx| p.anvil_grid.read(cx).card_builds),
builds
);
hover(cx, "banner-title");
finish_fade(cx);
assert_eq!(held_splashes(&page, cx), ["Briar.50.30.jpg"]);
// With every card grey, the first card in the chosen sort supplies the art.
let mut pick = with_bans_and_ally(&[233], 233);
pick.anvil_champions = Some(vec![16, 64]);
send(&page, cx, &pick);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx).last().unwrap(), "LeeSin.50.30.jpg");
}
#[gpui::test]
async fn the_tick_stays_with_the_grid_that_lit_it(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
cx.simulate_resize(size(px(1280.), px(1300.)));
draw(cx);
click_others(cx);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let hover = |cx: &mut VisualTestContext, id: &'static str| {
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
};
// From an Anvil champion straight to a card of « Autres champions », and back.
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
hover(cx, "card-103");
assert_eq!(lit(cx), Some(103));
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
// Folding « Autres champions » under a still pointer leaves the Anvil champion's tick
// lit: the grid it replaces only puts out a tick it lit.
page.update(cx, |page, cx| page.toggle_others(cx));
draw(cx);
assert!(!others_open(&page, cx));
assert_eq!(lit(cx), Some(233));
// A key press ends every hover for GPUI until the pointer moves (the card's sheet goes
// too): the tick follows the card.
cx.update(|window, cx| {
let focus = page.read(cx).others_focus.clone();
focus.focus(window, cx);
});
activate(cx, "enter");
assert!(others_open(&page, cx));
assert_eq!(lit(cx), None);
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
}
@@ -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());
}
+351
View File
@@ -0,0 +1,351 @@
use super::page_fixtures::{
animations, center, draw, focus_sort, frame_after, hover, open_page_in_season, press, rise,
settle, sheet, sheet_champions, sheet_ids, show, statistics,
};
use arena_tracker_core::ChampionState;
use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
fn the_sheet_shows_on_hover_with_the_date_of_a_completed_champion_only(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
assert!(sheet_ids(cx, 12).is_empty(), "a sheet is built at rest");
let completed = center(cx, "card-1");
cx.simulate_mouse_move(completed, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [1]);
assert_eq!(sheet(cx, 1), Some(true));
let remaining = center(cx, "card-2");
cx.simulate_mouse_move(remaining, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(false));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(
sheet_ids(cx, 12).is_empty(),
"the sheet stays after the pointer left"
);
}
// The card under the pointer rises over the grid, from where the grid placed it, and settles
// back once left: the grid stays cached through it all, no card is built and no statistics
// are computed, and no frame is asked for once the cards are still.
#[gpui::test]
fn hovering_a_card_lifts_it_over_the_grid_which_is_not_drawn_again(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
settle(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let built = |cx: &mut VisualTestContext| {
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls)
})
};
let at_rest = built(cx);
hover(cx, "card-2");
assert_eq!(rise(cx, 2), Some(0.), "it jumped");
frame_after(cx, 100);
let rising = rise(cx, 2).expect("the card is not lifted");
assert!(rising > 0. && rising < 10., "{rising}");
// Its sheet slides up while it rises.
assert!(cx.debug_bounds("sheet-2").is_some());
settle(cx);
assert_eq!(rise(cx, 2), Some(10.));
// To the next card: it rises while the one left settles back.
hover(cx, "card-3");
frame_after(cx, 100);
assert!(rise(cx, 2).is_some_and(|rise| rise > 0. && rise < 10.));
assert!(rise(cx, 3).is_some_and(|rise| rise > 0. && rise < 10.));
settle(cx);
assert_eq!(rise(cx, 2), None, "the card left stayed lifted");
assert_eq!(rise(cx, 3), Some(10.));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
settle(cx);
assert_eq!(rise(cx, 3), None);
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for at rest");
assert_eq!(built(cx), at_rest, "the grid was drawn again");
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
#[gpui::test]
fn a_greyed_card_rises_less_with_the_same_sheet(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
// The first champion is Completed: greyed.
hover(cx, "card-1");
assert_eq!(sheet_ids(cx, 12), [1]);
assert_eq!(sheet(cx, 1), Some(true));
assert_eq!(rise(cx, 1), Some(4.));
}
#[gpui::test]
fn without_animations_the_sheet_shows_at_once_and_the_card_stays_put(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
settle(cx);
animations(cx, false);
draw(cx);
hover(cx, "card-2");
assert_eq!(rise(cx, 2), Some(0.));
assert!(cx.debug_bounds("sheet-2").is_some(), "the sheet waits");
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for");
// Left, it is gone at once.
hover(cx, "card-3");
assert_eq!(rise(cx, 2), None);
assert_eq!(rise(cx, 3), Some(0.));
}
// A lifted card shows the grid's card as it is now: a first top 1 meanwhile greys it and
// dates its sheet.
#[gpui::test]
fn a_lifted_card_shows_its_figures_as_they_change(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
hover(cx, "card-2");
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(false));
assert_eq!(rise(cx, 2), Some(10.));
let mut rows = sheet_champions(12);
rows[1].state = Some(ChampionState::Completed);
rows[1].challenge = rows[0].challenge;
show(&page, cx, statistics(2, 12, rows));
draw(cx);
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(true));
assert_eq!(rise(cx, 2), Some(4.));
}
// A card the keyboard lifted goes down as soon as the pointer moves.
#[gpui::test]
fn the_pointer_takes_over_from_the_keyboard(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
focus_sort(&page, cx);
press(cx, "tab");
assert_eq!(sheet_ids(cx, 12), [1]);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(
sheet_ids(cx, 12).is_empty(),
"the keyboard's card stayed lifted"
);
}
// A wheel at the top of the list moves no card: the card is put down all the same, while
// its tick stays lit as it is still under the pointer.
#[gpui::test]
fn a_wheel_puts_the_card_down_even_at_the_end_of_the_list(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
hover(cx, "card-2");
settle(cx);
assert_eq!(rise(cx, 2), Some(10.));
let at = center(cx, "card-2");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(400.))),
..Default::default()
});
draw(cx);
assert_eq!(rise(cx, 2), None);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(2));
}
#[gpui::test]
fn turning_animations_off_puts_a_rising_card_where_it_goes(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
hover(cx, "card-2");
frame_after(cx, 50);
animations(cx, false);
draw(cx);
assert_eq!(rise(cx, 2), Some(0.));
assert!(cx.debug_bounds("sheet-2").is_some());
// The frame asked for before is the last.
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for");
}
#[gpui::test]
fn scrolling_the_grid_hides_the_sheet_of_the_card_that_was_under_the_pointer(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let over = center(cx, "card-1");
cx.simulate_mouse_move(over, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 170), [1]);
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-20.))),
..Default::default()
});
draw(cx);
// At once, with no card settling back from where it was.
assert!(
cx.debug_bounds("lifted-1").is_none(),
"the card stayed lifted"
);
assert!(sheet_ids(cx, 170).is_empty(), "the sheet stuck to its card");
}
#[gpui::test]
fn the_sheet_shows_on_keyboard_focus_and_follows_tab(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 40, sheet_champions(40)));
draw(cx);
focus_sort(&page, cx);
draw(cx);
assert!(sheet_ids(cx, 40).is_empty());
// From the sort selector, the last stop before the cards, Tab reaches the first card, the Completed one.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
// The next card: the previous sheet goes, the remaining champion has no date.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [2]);
assert_eq!(sheet(cx, 2), Some(false));
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [3]);
// Shift-Tab goes back.
press(cx, "shift-tab");
press(cx, "shift-tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
}
#[gpui::test]
fn tab_scrolls_the_row_of_the_next_card_into_view(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
focus_sort(&page, cx);
draw(cx);
assert!(
cx.debug_bounds("card-25").is_none(),
"card 25 is already built"
);
assert_eq!(grid.read_with(cx, |grid, _| grid.scrolled()), px(0.));
// Rows of 6: the 25th card opens the 5th row, below what 860 px shows.
for _ in 0..25 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 170), [25]);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
let bounds = cx.debug_bounds("card-25").expect("the row was not built");
assert!(bounds.bottom() <= px(860.), "{bounds:?}");
// Back across the row boundary, upwards.
for _ in 0..6 {
press(cx, "shift-tab");
}
assert_eq!(sheet_ids(cx, 170), [19]);
let bounds = cx.debug_bounds("card-19").expect("the row was not built");
assert!(bounds.origin.y >= px(0.), "{bounds:?}");
}
#[gpui::test]
fn tab_leaves_the_grid_after_its_last_card(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 3, sheet_champions(3)));
draw(cx);
focus_sort(&page, cx);
for _ in 0..3 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 3), [3]);
press(cx, "tab");
assert!(sheet_ids(cx, 3).is_empty(), "the focus stayed in the grid");
}
// Hovering the cards does not draw the grid again; tabbing over them does (GPUI draws the
// whole window when the focus moves). Neither builds the cards again nor computes any
// statistics.
#[gpui::test]
fn showing_a_sheet_does_not_rebuild_the_cards_nor_recompute_the_statistics(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
// The Completed card's crown is loaded, which draws the grid again.
settle(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
for id in ["card-1", "card-2", "card-1"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
settle(cx);
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
focus_sort(&page, cx);
for _ in 0..10 {
press(cx, "tab");
}
// The key presses ended the pointer's hover: the focused card alone shows its sheet.
assert_eq!(sheet_ids(cx, 170), [10]);
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
@@ -0,0 +1,225 @@
use super::champ_select_fixtures::{
ANVIL_A_TO_Z, OTHERS_A_TO_Z, anvil_cards, capture, click_others, frames, ids, leave,
others_cards, others_open, page_in_champ_select, read_champ_select, scroll_champ_select_down,
search_others, send,
};
use super::page_fixtures::{
center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show,
statistics,
};
use crate::champion_table::tests::row;
use crate::page::Tab;
use arena_tracker_core::ChampSelectReader;
use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px};
use std::cell::RefCell;
use std::rc::Rc;
// As the home grid's test: hovering the cards of « Autres champions » does not draw its grid
// again, and neither it nor scrolling costs statistics or cards. (The capture's catalog is too short for
// the list to scroll: the wheel still reaches the grid, which is what clears its hover.)
#[gpui::test]
async fn hovering_or_scrolling_others_does_not_recompute_the_statistics(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
scroll_champ_select_down(&mut window);
let cx = &mut window;
let grid = page.read_with(cx, |p, _| p.others_grid.clone());
let generation = page.read_with(cx, |p, _| p.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(set_cards > 0 && renders > 0);
let hovers = count_hovers(&grid, cx);
for id in ["card-103", "card-12", "card-103"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
settle(cx);
assert!(hovers.get() > 0, "no card was hovered");
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
let over = center(cx, "card-103");
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
..Default::default()
});
draw(cx);
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |p, _| p.stats_generation),
generation,
"the statistics were computed again"
);
assert!(!page.read_with(cx, |p, _| p.stats_job.running()));
}
#[gpui::test]
async fn the_search_of_others_filters_only_that_section(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
let anvil_before = anvil_cards(&page, &mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
search_others(&page, &mut window, "ahr");
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// By alias: « cow » is Alistar's.
search_others(&page, &mut window, "cow");
assert_eq!(grid_names(&grid, &mut window), ["Alistar"]);
// An Anvil champion is not in this section, whoever searches for it.
search_others(&page, &mut window, "xz");
assert!(grid_names(&grid, &mut window).is_empty());
assert!(window.debug_bounds("no-champion").is_some());
// The anvil row and the home's search are intact.
assert_eq!(anvil_cards(&page, &mut window), anvil_before);
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
page.read_with(&window, |p, cx| {
assert!(p.home_search_input.read(cx).value().is_empty())
});
search_others(&page, &mut window, "");
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
}
#[gpui::test]
async fn a_new_champ_select_folds_others_and_empties_its_search(cx: &mut TestAppContext) {
let frames = frames();
let (page, mut window) = page_in_champ_select(cx, &frames[0]).await;
let fresh = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| {
assert!(!p.others_open);
assert!(p.others_search_input.read(cx).value().is_empty());
assert_eq!(p.others_grid.read(cx).renders, 0);
assert!(p.others_grid.read(cx).shown_cards().is_empty());
})
};
// The frames of the same champ select keep it open, with its search.
click_others(&mut window);
search_others(&page, &mut window, "ahr");
send(&page, &mut window, &frames[1]);
draw(&mut window);
assert!(others_open(&page, &mut window));
assert_eq!(others_cards(&page, &mut window).len(), 1);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// Leaving, then entering again.
leave(&page, &mut window);
draw(&mut window);
fresh(&mut window);
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("others-toggle").is_some());
assert!(window.debug_bounds("card-103").is_none());
// The champ select of another Riot ID.
click_others(&mut window);
search_others(&page, &mut window, "cow");
let live = Some(("Autre#EUW".to_string(), frames[0].clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
fresh(&mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("card-103").is_none());
}
#[gpui::test]
async fn others_lists_every_champion_when_the_anvil_list_is_unknown(cx: &mut TestAppContext) {
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(&ChampSelectReader::default(), session, None);
let (page, mut window) = page_in_champ_select(cx, &pick).await;
page.read_with(&window, |p, _| {
assert_eq!(p.others_title(), "Tous les champions")
});
click_others(&mut window);
let all: Vec<u32> = page.read_with(&window, |p, _| {
p.stats
.as_ref()
.unwrap()
.rows
.iter()
.map(|r| r.champion.id)
.collect()
});
assert_eq!(all.len(), 9);
assert_eq!(ids(&others_cards(&page, &mut window)), all);
assert!(anvil_cards(&page, &mut window).is_empty());
assert!(window.debug_bounds("card-233").is_some());
}
#[gpui::test]
fn others_builds_only_the_visible_cards_and_hovering_elsewhere_does_not_draw_them(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_page_in_season(cx);
send(&page, &mut window, &frames()[0]);
// The statistics of the Account, as the worker would give them: 170 champions, most
// of them without an anvil.
show(&page, &mut window, statistics(0, 170, champions(170)));
draw(&mut window);
click_others(&mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let (built, renders) = grid.read_with(&window, |grid, _| (grid.card_builds, grid.renders));
// 170 champions less the Anvil ones the statistics know: 5, 16, 64 and 68.
assert_eq!(
grid.read_with(&window, |grid, _| grid.shown_cards().len()),
166
);
assert!(built > 0 && built <= 8 * 6, "{built} cards built for 170");
assert!(renders > 0);
// Hovering the header, outside the cards, draws the page and not the cards.
let toggle = center(&mut window, "others-toggle");
for dx in 0..5 {
window.simulate_mouse_move(
point(toggle.x + px(dx as f32 * 7.), toggle.y),
None,
Modifiers::none(),
);
draw(&mut window);
}
assert_eq!(grid.read_with(&window, |grid, _| grid.renders), renders);
}
#[gpui::test]
fn no_champ_select_changes_nothing(cx: &mut TestAppContext) {
let (page, mut window) = open_page_in_season(cx);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &crate::page::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
show(&page, &mut window, statistics(0, 1, vec![row("Ahri")]));
let generation = page.read_with(&window, |p, _| p.stats_generation);
leave(&page, &mut window);
draw(&mut window);
assert!(entered.borrow().is_empty());
page.read_with(&window, |p, _| {
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.stats_generation, generation);
assert_eq!(p.anvil_line(), None);
});
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());
}
@@ -0,0 +1,377 @@
use super::banner_fixtures::{banner, splash};
use super::champ_select_fixtures::{
ANVIL, ANVIL_A_TO_Z, anvil_cards, bounds, capture, frames, ids, joueur_tracker,
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};
use crate::card::{ASPECT, Reason};
use crate::card_images::tests::TestDir;
use crate::page::Tab;
use arena_tracker_core::{ChampSelectReader, StateFilter};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
async fn the_champ_select_banner_follows_the_arena_capture(cx: &mut TestAppContext) {
let dir = TestDir::new("champ-select-banner");
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let mut stats = page.read_with(&window, |p, _| p.home_statistics().unwrap().clone());
for row in &mut stats.rows {
row.splash = Some(splash(dir.path(), &row.champion.key));
}
show(&page, &mut window, stats);
page.update(&mut window, |p, cx| {
p.home_season = Some("Saison 2 2026".into());
p.prepare_champ_select(cx);
});
// The splash the banner shows, or fades to.
let art = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| {
let target = p.banner_art.read(cx).target.clone()?;
Some(target.path.file_name()?.to_string_lossy().into_owned())
})
};
let ring_anvil = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| p.ring.read(cx).anvil().map(<[u32]>::to_vec))
};
let check = |window: &mut VisualTestContext, frame: usize, k: usize, splash: &str| {
let text = banner(&page, window);
assert_eq!(
text.season.as_ref(),
"SAISON 2 · 2026 · 1 / 9 validés",
"frame {frame}"
);
assert_eq!(text.title.text.as_ref(), "Sélection des champions");
let plural = if k > 1 { "s" } else { "" };
assert_eq!(
text.detail.text.as_ref(),
format!("Champions de l'Enclume · {k} à valider et disponible{plural}"),
"frame {frame}"
);
assert!(text.last_match.is_none());
assert_eq!(
art(window).as_deref(),
Some(format!("{splash}.50.30.jpg").as_str()),
"frame {frame}"
);
};
// The capture's own hand: Soraka is validated, Lee Sin, Rumble and Xin Zhao are not
// offered, so only Briar is left. The bans (Alistar, Swain) and the ally's Morgana are
// not in the hand: k stays at 1, before and after the ally's confirmation.
draw(&mut window);
let first = bounds(&mut window);
for (frame, pick) in frames().iter().enumerate() {
send(&page, &mut window, pick);
draw(&mut window);
check(&mut window, frame, 1, "Briar");
let places = places(&page, &mut window, &first, &ANVIL_A_TO_Z);
assert_eq!(bounds(&mut window), places, "frame {frame}");
assert_eq!(ring_anvil(&mut window), Some(ANVIL.to_vec()));
}
// A hovered card supplies the illustration; without one, the default comes back.
let at = center(&mut window, "card-64");
window.simulate_mouse_move(at, None, Modifiers::none());
draw(&mut window);
assert_eq!(art(&mut window).as_deref(), Some("LeeSin.50.30.jpg"));
window.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(&mut window);
assert_eq!(art(&mut window).as_deref(), Some("Briar.50.30.jpg"));
// The same frames with the banned Alistar and the ally's Morgana in the hand (A to Z:
// Alistar, Briar, Morgana, Soraka): Alistar's ban, then Morgana's confirmation, lower k
// and move the default illustration on. The cards stay.
let hand = [12, 16, 25, 233];
let cards = ["card-12", "card-233", "card-25", "card-16"];
let mut picks = frames();
for pick in &mut picks {
pick.anvil_champions = Some(hand.to_vec());
}
let hand_bounds = |window: &mut VisualTestContext| -> Vec<_> {
cards
.iter()
.map(|id| window.debug_bounds(id).expect("the card is not drawn"))
.collect()
};
send(&page, &mut window, &picks[0]);
draw(&mut window);
let first = hand_bounds(&mut window);
let expected = [
(3, "Alistar"),
(2, "Briar"),
(2, "Briar"),
(1, "Briar"),
(1, "Briar"),
];
for (frame, (pick, (k, splash))) in picks.iter().zip(expected).enumerate() {
send(&page, &mut window, pick);
draw(&mut window);
check(&mut window, frame, k, splash);
let places = places(&page, &mut window, &first, &[12, 233, 25, 16]);
assert_eq!(hand_bounds(&mut window), places, "frame {frame}");
assert_eq!(ring_anvil(&mut window), Some(hand.to_vec()));
}
// A list the client does not send: #74's message, and no tick dimmed.
let mut unknown = picks[4].clone();
unknown.anvil_champions = None;
send(&page, &mut window, &unknown);
assert_eq!(
banner(&page, &mut window).detail.text.as_ref(),
"Champions de l'Enclume non communiqués par le client"
);
assert_eq!(ring_anvil(&mut window), None);
leave(&page, &mut window);
assert_eq!(ring_anvil(&mut window), None);
}
#[gpui::test]
async fn the_arena_capture_fills_the_anvil_row_in_the_homes_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
// The home's own order, which the row follows.
let home_order: Vec<u32> = page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
rows.map(|row| row.champion.id)
.filter(|id| ANVIL.contains(id))
.collect()
});
assert_eq!(home_order, ANVIL_A_TO_Z);
let frames = frames();
assert_eq!(frames.len(), 5);
send(&page, &mut window, &frames[0]);
// Until the statistics are there, the row is replaced by what is missing.
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some("Compte indisponible"))
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let first = bounds(&mut window);
// Never greyed by the champ select: 233 and 16 are offered, the rest is not offered.
let baseline = [
(233, vec![]),
(64, vec![Reason::NotOffered]),
(68, vec![Reason::NotOffered]),
(16, vec![Reason::Completed]),
(5, vec![Reason::NotOffered]),
];
for (frame, pick) in frames.iter().enumerate() {
if frame > 0 {
send(&page, &mut window, pick);
}
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
// 12 (banned), 25 (ally) and 50 (banned) are not Anvil champions: never in the row.
assert_eq!(ids(&cards), ANVIL_A_TO_Z, "frame {frame}");
for (id, expected) in &baseline {
assert_eq!(
&reasons(&cards, *id),
expected,
"frame {frame}, champion {id}"
);
}
// The cards keep their place.
let places = places(&page, &mut window, &first, &ANVIL_A_TO_Z);
assert_eq!(bounds(&mut window), places, "frame {frame}");
}
// The marks come with the Challenge of the signed-in Account.
let cards = anvil_cards(&page, &mut window);
let mark = |id| cards.iter().find(|c| c.id == id).unwrap().marks;
assert!(mark(16).completed && mark(16).won);
assert!(mark(233).played && !mark(233).completed);
assert!(!mark(64).played);
// Reasons add up: 16 is Completed and banned, 233 banned and confirmed by an ally. The
// labels change and the cards stay.
send(&page, &mut window, &with_bans_and_ally(&[16, 233, 12], 233));
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
assert_eq!(reasons(&cards, 16), [Reason::Completed, Reason::Banned]);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
assert_eq!(reasons(&cards, 64), [Reason::NotOffered]);
// Briar, taken by an ally, rests 8 px lower than the others, which do not move.
let mut lowered = first.clone();
lowered[0].origin.y += px(8.);
assert_eq!(bounds(&mut window), lowered);
// The cards are as big as the home's, on one row of six at 1280 px.
let (width, height) = (first[0].size.width.as_f32(), first[0].size.height.as_f32());
assert!((height - width / ASPECT).abs() < 1., "{width} x {height}");
assert_eq!(first[0].origin.y, first[1].origin.y);
let gap = (first[1].origin.x - first[0].origin.x).as_f32() - width;
assert!((gap - 14.).abs() < 1., "gap {gap}");
}
#[gpui::test]
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());
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
// Autre, on « Toutes les Saisons », with a filter and a search on the home.
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Autre".into());
p.season = SeasonScope::AllSeasons;
p.home_filter = StateFilter::Completed;
p.reload(w, cx);
});
input.update(cx, |input, cx| input.set_value("ah", w, cx));
});
page.read_with(&window, |p, _| {
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.tab, Tab::Statistics);
});
draw(&mut window);
let frames = frames();
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
// « 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.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 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());
// 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));
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, cx| {
// As before the champ select, with « Tous » and no search on the home.
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.home_filter, StateFilter::All);
assert!(p.home_search_input.read(cx).value().is_empty());
assert_eq!(p.home_shown_count.as_ref(), "9");
assert_eq!(p.home_grid.read(cx).names().len(), 9);
assert_eq!(p.banner.title.text.as_ref(), "0 / 9 champions validés");
assert!(p.anvil_grid.read(cx).names().is_empty());
});
assert_eq!(
home_grid.read_with(&window, |grid, _| grid.names().len()),
9
);
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("card-103").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
// Another champ select starts clean.
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 16), [Reason::Completed]);
assert_eq!(reasons(&cards, 233), []);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
}
#[gpui::test]
async fn an_unknown_or_empty_anvil_list_is_said_soberly(cx: &mut TestAppContext) {
cx.executor().allow_parking();
for (anvil, line) in [
(None, "Champions de l'Enclume non communiqués par le client"),
(
Some("[]"),
"Aucun Champion de l'Enclume dans cette sélection",
),
] {
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(
&ChampSelectReader::default(),
session,
anvil.map(str::to_string),
);
send(&page, &mut window, &pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some(line))
});
// No row, and no champion is presented as without an anvil.
assert!(anvil_cards(&page, &mut window).is_empty());
assert_eq!(
window.debug_bounds("anvil-notice").is_some(),
anvil.is_some()
);
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("card-103").is_none());
assert!(window.debug_bounds("card-16").is_none());
}
}
#[gpui::test]
async fn missing_statistics_are_said_once_and_leave_nothing_to_browse(cx: &mut TestAppContext) {
cx.executor().allow_parking();
// No current Season: the header says so, and the Anvil area does not say it again.
let (page, mut window) = open_page(cx);
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.stats_notice(),
Some(crate::page::home::StatsNotice::NoSeason)
);
});
assert!(window.debug_bounds("no-season").is_some());
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("others-toggle").is_none());
// The statistics are on their way: the area says so, and there is nothing to browse yet.
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.anvil_line().as_deref(),
Some("Chargement des statistiques…")
);
});
assert!(window.debug_bounds("no-season").is_none());
assert!(window.debug_bounds("anvil-notice").is_some());
assert!(window.debug_bounds("others-toggle").is_none());
// Once they are there, the section is offered.
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("others-toggle").is_some());
}
@@ -0,0 +1,471 @@
use super::page_fixtures::{MATCH_1750, center, draw, frame_after, open_page_with_tracker, season};
use crate::card::{Card, Reason};
use crate::card_images::tests::PORTRAIT_JPEG;
use crate::page::Page;
use arena_tracker_core::{
Account, ChampSelect, ChampSelectReader, Champion, ChampionCatalog, ChampionSource,
ClientError, MatchHistorySource, SourceError, Tracker,
};
use gpui_kit::{
Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ScrollDelta, ScrollEvent,
TestAppContext, VisualTestContext, WindowVisibility, point, px,
};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub(super) const JOUEUR: &str = "Joueur#EUW";
pub(super) const ANVIL: [u32; 5] = [233, 64, 5, 16, 68];
/// The Anvil champions of the capture in the order of the home: A to Z by name.
pub(super) const ANVIL_A_TO_Z: [u32; 5] = [233, 64, 68, 16, 5];
pub(super) const ANVIL_CARDS: [&str; 5] = ["card-233", "card-64", "card-68", "card-16", "card-5"];
/// (id, key, name): the champions of the capture.
pub(super) const CATALOG: [(u32, &str, &str); 9] = [
(12, "Alistar", "Alistar"),
(16, "Soraka", "Soraka"),
(25, "Morgana", "Morgana"),
(50, "Swain", "Swain"),
(64, "LeeSin", "Lee Sin"),
(5, "XinZhao", "Xin Zhao"),
(68, "Rumble", "Rumble"),
(103, "Ahri", "Ahri"),
(233, "Briar", "Briar"),
];
/// Joueur completed 16 (a top 1) and played 233 (a 4th place).
pub(super) struct JoueurHistory;
impl MatchHistorySource for JoueurHistory {
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> {
Ok(if puuid == "Joueur" && queue_id == 1750 && start == 0 {
vec!["EUW1_1".into(), "EUW1_2".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let (champion, name, placement) = match id {
"EUW1_1" => (16, "Soraka", 1),
"EUW1_2" => (233, "Briar", 4),
_ => return Err(SourceError::NotFound),
};
let raw = MATCH_1750.replace("fixture-puuid-self", "Joueur");
let mut payload: Value = serde_json::from_str(&raw).unwrap();
payload["metadata"]["matchId"] = id.into();
for player in payload["info"]["participants"].as_array_mut().unwrap() {
if player["puuid"] == "Joueur" {
player["championId"] = champion.into();
player["championName"] = name.into();
player["placement"] = placement.into();
player["win"] = (placement <= 3).into();
}
}
Ok(payload.to_string())
}
fn champion_mastery(&self, _: &str, puuid: &str) -> Result<Vec<(u32, u64)>, SourceError> {
Ok(if puuid == "Joueur" {
MASTERY.to_vec()
} else {
Vec::new()
})
}
}
/// Joueur's Mastery Points. Xin Zhao (5) and Morgana (25) are missing from the list: known,
/// no points.
pub(super) const MASTERY: [(u32, u64); 7] = [
(64, 120_000),
(16, 40_000),
(50, 9_000),
(233, 5_000),
(68, 900),
(12, 300),
(103, 100),
];
/// The champions without an anvil of the capture by Mastery Points.
pub(super) const OTHERS_BY_MASTERY: [u32; 4] = [50, 12, 103, 25];
pub(super) const ALL_A_TO_Z: [&str; 9] = [
"Ahri", "Alistar", "Briar", "Lee Sin", "Morgana", "Rumble", "Soraka", "Swain", "Xin Zhao",
];
pub(super) struct Catalog;
impl ChampionSource for Catalog {
fn latest_version(&self) -> Result<String, SourceError> {
Ok("1.0".into())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
Ok(ChampionCatalog {
version: version.into(),
champions: CATALOG
.iter()
.map(|&(id, key, name)| Champion {
id,
key: key.into(),
name: name.into(),
})
.collect(),
})
}
fn portrait(&self, _: &str, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
fn card_portrait(&self, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
fn splash(&self, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
}
/// The tracker of Joueur (and of Autre, who has played nothing), on the catalog.
pub(super) fn joueur_tracker() -> Tracker {
joueur_tracker_with(false)
}
/// `mastery`: Joueur is the Account being followed and its points were fetched.
pub(super) fn joueur_tracker_with(mastery: bool) -> Tracker {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
// One folder per tracker (the tests run in parallel), removed once the catalog is stored.
let portraits = crate::card_images::tests::TestDir::new("page-tracker");
let tracker = tracker.with_champions(Box::new(Catalog), portraits.path().to_path_buf());
tracker.refresh_champions().unwrap();
if mastery {
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
// Without a client, a round adopts the Riot ID it is given, then asks for the points.
tracker.follow_client(0, Some(JOUEUR), &mut |_| {});
assert!(tracker.mastery("Joueur").unwrap().is_some());
} else {
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
}
tracker
}
pub(super) fn capture() -> Value {
serde_json::from_str(include_str!(
"../../../../core/tests/fixtures/client/arena_champ_select.json"
))
.unwrap()
}
/// The champ select as the page gets it from a session, the lists being those of the capture
/// but the Anvil one.
pub(super) fn read_champ_select(
reader: &ChampSelectReader,
session: Value,
anvil: Option<String>,
) -> ChampSelect {
let capture = capture();
reader.set_session(session);
reader
.read(
|| Err(ClientError::Absent),
|| {
Ok((
capture["pickableChampionIds"].to_string(),
capture["disabledChampionIds"].to_string(),
anvil,
))
},
)
.unwrap()
}
/// The five frames of the capture, read through one reader as the follower does.
pub(super) fn frames() -> Vec<ChampSelect> {
let capture = capture();
let reader = ChampSelectReader::default();
capture["sessions"]
.as_array()
.unwrap()
.iter()
.map(|session| {
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&reader, session.clone(), anvil)
})
.collect()
}
/// Frame 0 with these completed bans, and `ally` confirmed.
pub(super) fn with_bans_and_ally(bans: &[u32], ally: u32) -> ChampSelect {
let capture = capture();
let mut session = capture["sessions"][0].clone();
session["actions"] = json!([bans
.iter()
.map(|id| json!({"type": "ban", "championId": id, "completed": true}))
.collect::<Vec<_>>()]);
session["myTeam"][1]["championId"] = ally.into();
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&ChampSelectReader::default(), session, anvil)
}
pub(super) fn send(page: &Entity<Page>, window: &mut VisualTestContext, pick: &ChampSelect) {
let live = Some((JOUEUR.to_string(), pick.clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
}
/// Ends the champ select, and lets the hand leave and the home come back.
pub(super) fn leave(page: &Entity<Page>, window: &mut VisualTestContext) {
start_leaving(page, window);
finish_motion(page, window);
}
/// Ends the champ select, without waiting for the hand to leave.
pub(super) fn start_leaving(page: &Entity<Page>, window: &mut VisualTestContext) {
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(None), w, cx)
})
});
}
/// Lets the champ select's entry or exit end, and the veil lift.
pub(super) fn finish_motion(page: &Entity<Page>, window: &mut VisualTestContext) {
for _ in 0..60 {
let moving = page.read_with(window, |p, cx| {
p.leave.is_some() || p.fade.is_some() || p.stage_moving(cx)
});
if !moving {
return;
}
frame_after(window, 50);
}
panic!("the champ select's motion did not end");
}
pub(super) fn anvil_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.anvil_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
pub(super) fn ids(cards: &[Card]) -> Vec<u32> {
cards.iter().map(|card| card.id).collect()
}
pub(super) fn reasons(cards: &[Card], id: u32) -> Vec<Reason> {
cards.iter().find(|c| c.id == id).unwrap().reasons.clone()
}
/// Where the hand's cards `ids` rest, from `first`: in their place, but a card an ally took,
/// 8 px lower (#87).
pub(super) fn places(
page: &Entity<Page>,
window: &mut VisualTestContext,
first: &[gpui_kit::Bounds<gpui_kit::Pixels>],
ids: &[u32],
) -> Vec<gpui_kit::Bounds<gpui_kit::Pixels>> {
let cards = anvil_cards(page, window);
first
.iter()
.zip(ids)
.map(|(place, id)| {
let taken = reasons(&cards, *id).contains(&Reason::TakenByAlly);
let mut place = *place;
if taken {
place.origin.y += px(crate::card_grid::TAKEN_DROP);
}
place
})
.collect()
}
pub(super) fn bounds(window: &mut VisualTestContext) -> Vec<gpui_kit::Bounds<gpui_kit::Pixels>> {
ANVIL_CARDS
.iter()
.map(|id| window.debug_bounds(id).expect("the card is not drawn"))
.collect()
}
/// What the non-anvil champions of the capture are, in the home's order (A to Z by name).
pub(super) const OTHERS_A_TO_Z: [u32; 4] = [103, 12, 25, 50];
pub(super) fn others_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.others_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
pub(super) fn others_open(page: &Entity<Page>, window: &mut VisualTestContext) -> bool {
page.read_with(window, |p, _| p.others_open)
}
pub(super) fn click_others(window: &mut VisualTestContext) {
let toggle = center(window, "others-toggle");
window.simulate_click(toggle, Modifiers::none());
draw(window);
// The section's first layout says where its grid is: the frame after it builds the rows.
draw(window);
}
/// Scrolls the champ select's column to its end, over the banner: the open « Autres
/// champions » starts under the window's bottom edge.
pub(super) fn scroll_champ_select_down(window: &mut VisualTestContext) {
let banner = center(window, "banner");
window.simulate_event(ScrollEvent {
position: banner,
delta: ScrollDelta::Pixels(point(px(0.), px(-5000.))),
..Default::default()
});
draw(window);
}
/// Presses and releases `key` on the focused element, as the navigation's test does.
pub(super) fn activate(window: &mut VisualTestContext, key: &str) {
let keystroke =
window.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
window.simulate_event(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
});
window.simulate_event(KeyUpEvent { keystroke });
draw(window);
}
/// Tab, until the section's header has the focus.
pub(super) fn focus_others_toggle(page: &Entity<Page>, window: &mut VisualTestContext) {
for _ in 0..60 {
window.update(|w, cx| w.focus_next(cx));
draw(window);
if window.update(|w, cx| page.read(cx).others_focus.is_focused(w)) {
return;
}
}
panic!("Tab never reached « Autres champions »");
}
pub(super) fn search_others(page: &Entity<Page>, window: &mut VisualTestContext, text: &str) {
let input = page.read_with(window, |p, _| p.others_search_input.clone());
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
if !text.is_empty() {
window.simulate_input(text);
}
draw(window);
}
/// The page in the first frame of the capture, once its statistics are there.
pub(super) async fn page_in_champ_select(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
// The hand is dealt.
finish_motion(&page, &mut window);
(page, window)
}
/// Enters the champ select of `pick` with the window hidden in the notification area, then
/// shows it once the statistics are loaded, as #63 does: the entry starts at the test
/// clock's present, the hand already holding its cards.
pub(super) async fn entering(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
window.simulate_visibility_change(WindowVisibility::Hidden);
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
window.run_until_parked();
window.simulate_visibility_change(WindowVisibility::Visible);
draw(&mut window);
// The portraits looked for once (the catalog has none) draw the hand's grid again.
window.run_until_parked();
draw(&mut window);
(page, window)
}
/// How far below its place card `id` of the hand is drawn while it moves (above when
/// negative), if it is.
pub(super) fn below(cx: &mut VisualTestContext, id: u32) -> Option<f32> {
let moving = cx.debug_bounds(Box::leak(format!("moving-{id}").into_boxed_str()))?;
let place = cx
.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
.unwrap();
assert_eq!(moving.size, place.size, "the card changed size");
assert_eq!(moving.origin.x, place.origin.x, "the card left its column");
Some((moving.origin.y - place.origin.y).as_f32())
}
/// What the entry must not do again at each frame: compute the statistics, sort the cards,
/// draw the hand's grid or build its cards.
pub(super) fn computed(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> (u64, usize, bool, usize, usize) {
let hand = page.read_with(cx, |p, _| p.anvil_grid.clone());
let (renders, builds) = hand.read_with(cx, |grid, _| (grid.renders, grid.card_builds));
page.read_with(cx, |p, _| {
(
p.stats_generation,
p.reorders,
p.stats_job.running(),
renders,
builds,
)
})
}
/// Joueur's tracker on the catalog, with the card portraits of `keys` on disk under `dir`.
pub(super) fn tracker_with_portraits(dir: &Path, keys: &[&str]) -> Tracker {
let portraits = dir.join("portraits");
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)])
.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
let cards = portraits.join("cards");
std::fs::create_dir_all(&cards).unwrap();
for key in keys {
std::fs::write(cards.join(format!("{key}.jpg")), PORTRAIT_JPEG).unwrap();
}
tracker
}
pub(super) fn card_portrait(dir: &Path, key: &str) -> PathBuf {
dir.join("portraits")
.join("cards")
.join(format!("{key}.jpg"))
}
Loaded 100 of 338 files, more files were not shown because too many files have changed in this diff. Show more