From e56da040e5f33f1b3e07c1c1f316c78b2da40e89 Mon Sep 17 00:00:00 2001 From: TO Date: Sun, 22 Nov 2026 17:20:58 +0100 Subject: [PATCH] Address module split review on #103 --- crates/app/src/card_grid.rs | 4 +- .../src/card_grid/{placement.rs => layout.rs} | 0 crates/app/src/card_images.rs | 301 +------------- crates/app/src/card_images/tests.rs | 298 ++++++++++++++ crates/app/src/page.rs | 167 +++++++- crates/app/src/page/cards.rs | 141 +------ crates/app/src/page/champ_select/cards.rs | 142 +++++++ crates/app/src/page/champ_select/mod.rs | 95 +++++ .../motion.rs} | 41 +- crates/app/src/page/champ_select/render.rs | 175 ++++++++ crates/app/src/page/display.rs | 54 +-- crates/app/src/page/home.rs | 208 +++------- crates/app/src/page/home/banner.rs | 48 ++- crates/app/src/page/home/content.rs | 2 +- crates/app/src/page/hover.rs | 9 - crates/app/src/page/lifecycle.rs | 45 +++ crates/app/src/page/state.rs | 140 ------- crates/app/src/page/statistics.rs | 2 + crates/app/src/page/{ => statistics}/data.rs | 126 +++--- crates/app/src/page/tabs.rs | 103 ----- crates/app/src/page/tests.rs | 67 +--- crates/app/src/page/tests/account.rs | 16 +- crates/app/src/page/tests/banner.rs | 21 +- ...ntation_fixtures.rs => banner_fixtures.rs} | 81 +--- crates/app/src/page/tests/banner_scope.rs | 15 +- crates/app/src/page/tests/card_sheet.rs | 7 +- .../src/page/tests/champ_select_browsing.rs | 18 +- .../src/page/tests/champ_select_capture.rs | 16 +- .../src/page/tests/champ_select_fixtures.rs | 19 +- .../app/src/page/tests/champ_select_motion.rs | 17 +- .../app/src/page/tests/champ_select_others.rs | 11 +- crates/app/src/page/tests/grid.rs | 12 +- crates/app/src/page/tests/home.rs | 18 +- crates/app/src/page/tests/match_animation.rs | 16 +- crates/app/src/page/tests/navigation.rs | 10 +- .../tests/{fixtures.rs => page_fixtures.rs} | 34 +- crates/app/src/page/tests/portraits.rs | 14 +- crates/app/src/page/tests/sorting.rs | 17 +- crates/app/src/page/tests/sorting_fixtures.rs | 72 ++++ .../page/{updates.rs => worker_messages.rs} | 72 +--- crates/app/src/settings.rs | 34 +- crates/app/src/settings/store.rs | 6 +- crates/app/src/settings/tests.rs | 2 +- crates/app/src/stage.rs | 376 +----------------- crates/app/src/stage/hand.rs | 3 +- crates/app/src/stage/motion.rs | 373 +++++++++++++++++ crates/app/src/stage/tests.rs | 13 +- docs/performance.md | 2 +- docs/research/arena-match-statistics.md | 2 +- 49 files changed, 1842 insertions(+), 1623 deletions(-) rename crates/app/src/card_grid/{placement.rs => layout.rs} (100%) create mode 100644 crates/app/src/card_images/tests.rs create mode 100644 crates/app/src/page/champ_select/cards.rs create mode 100644 crates/app/src/page/champ_select/mod.rs rename crates/app/src/page/{stage_motion.rs => champ_select/motion.rs} (87%) create mode 100644 crates/app/src/page/champ_select/render.rs create mode 100644 crates/app/src/page/lifecycle.rs delete mode 100644 crates/app/src/page/state.rs rename crates/app/src/page/{ => statistics}/data.rs (78%) delete mode 100644 crates/app/src/page/tabs.rs rename crates/app/src/page/tests/{presentation_fixtures.rs => banner_fixtures.rs} (63%) rename crates/app/src/page/tests/{fixtures.rs => page_fixtures.rs} (93%) create mode 100644 crates/app/src/page/tests/sorting_fixtures.rs rename crates/app/src/page/{updates.rs => worker_messages.rs} (56%) create mode 100644 crates/app/src/stage/motion.rs diff --git a/crates/app/src/card_grid.rs b/crates/app/src/card_grid.rs index 133b659..0949151 100644 --- a/crates/app/src/card_grid.rs +++ b/crates/app/src/card_grid.rs @@ -34,8 +34,8 @@ mod geometry; use geometry::{MAX_COLUMNS, Metrics}; pub use geometry::{MAX_WIDTH, TAKEN_DROP, row_height}; -mod placement; -pub use placement::{CardHovered, Placed, Placements, PutDown}; +mod layout; +pub use layout::{CardHovered, Placed, Placements, PutDown}; /// What makes one card reachable with the keyboard: its handle, and the subscriptions that lift /// it while the keyboard is on it. diff --git a/crates/app/src/card_grid/placement.rs b/crates/app/src/card_grid/layout.rs similarity index 100% rename from crates/app/src/card_grid/placement.rs rename to crates/app/src/card_grid/layout.rs diff --git a/crates/app/src/card_images.rs b/crates/app/src/card_images.rs index 9c68b94..2f9b918 100644 --- a/crates/app/src/card_images.rs +++ b/crates/app/src/card_images.rs @@ -152,303 +152,4 @@ impl CardImages { } #[cfg(test)] -pub(crate) mod tests { - 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>, - } - - impl Render for Host { - fn render(&mut self, _: &mut Window, _: &mut Context) -> 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, Entity, 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, cx: &mut VisualTestContext) -> Entity { - 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 { - (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 { - 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> = - 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))); - } -} +pub(crate) mod tests; diff --git a/crates/app/src/card_images/tests.rs b/crates/app/src/card_images/tests.rs new file mode 100644 index 0000000..d0c71d5 --- /dev/null +++ b/crates/app/src/card_images/tests.rs @@ -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>, +} + +impl Render for Host { + fn render(&mut self, _: &mut Window, _: &mut Context) -> 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, Entity, 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, cx: &mut VisualTestContext) -> Entity { + 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 { + (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 { + 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> = + 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))); +} diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index 8b2700c..03b8486 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -1,13 +1,12 @@ //! The page and its two tabs: the shared state, the header row with its navigation and the -//! banners. `home` (which also holds the champ select's sections) and `statistics` render what -//! is under the banners. +//! alerts. `home`, `champ_select` and `statistics` render the content under the alerts. use crate::banner_art::BannerArt; use crate::card::Card; use crate::card_grid::{CardGrid, CardHovered}; use crate::card_lift::Lifts; use crate::champion_table::ChampionTable; -use crate::motion::{Deferred, Fade, MatchAnimation, MatchEnd}; +use crate::motion::{Deferred, Fade, FadePhase, MatchAnimation, MatchEnd}; use crate::ring::Ring; use crate::stage::{Entry, Leave, Taken}; use crate::worker::{LiveChampSelect, Msg, RefreshGate}; @@ -15,11 +14,12 @@ use arena_tracker_core::{ Account, ChampionSearch, ChampionSort, Format, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, }; +use gpui_kit::base::Button as BaseButton; use gpui_kit::base::async_util::Sender; use gpui_kit::component::input::InputState; -#[cfg(test)] -use gpui_kit::component::select::SelectEvent; use gpui_kit::component::select::{SelectItem, SelectState}; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use statistics::ChartsRow; use std::collections::HashMap; @@ -313,15 +313,162 @@ pub struct Page { } mod cards; -mod data; +mod champ_select; mod display; mod hover; +mod lifecycle; mod playback; mod setup; -mod stage_motion; -mod state; -mod tabs; -mod updates; +mod worker_messages; #[cfg(test)] mod tests; + +impl Page { + /// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them. + fn navigation(&self, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let (ring, muted, active, active_foreground, hover, hover_foreground) = ( + theme.ring, + theme.tab_foreground, + theme.tab_active, + theme.tab_active_foreground, + theme.accent, + theme.accent_foreground, + ); + let tabs = [ + ("tab-challenge", "Défi", Tab::Challenge), + ("tab-statistics", "Statistiques", Tab::Statistics), + ]; + div() + .h_flex() + .gap_1() + .flex_shrink_0() + .children(tabs.map(|(id, label, tab)| { + let current = self.tab == tab; + // The champ select takes the window: « Statistiques » waits for its end. + let disabled = tab == Tab::Statistics && self.in_champ_select(); + BaseButton::new(id) + .disabled(disabled) + .px_3() + .py_1() + .rounded_md() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + // Always bordered, so the focus ring does not shift the label. + .border_1() + .border_color(transparent_black()) + .focus_visible(|style| { + style.border_color(if current { active_foreground } else { ring }) + }) + .text_color(if current { active_foreground } else { muted }) + .when(current, |button| button.bg(active)) + .when(!current && !disabled, |button| { + button.hover(|style| style.bg(hover).text_color(hover_foreground)) + }) + .when(disabled, |button| button.opacity(0.5)) + .accessibility_label(label) + .debug_selector(|| id.into()) + .child(label) + .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx))) + })) + } + + fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context) { + // The champ select takes the window: the Statistics tab waits for its end. + if tab == Tab::Statistics && self.in_champ_select() { + return; + } + if self.tab != tab { + self.tab = tab; + // The grids leave under the veil: no card stays lifted over it. + self.lifts.clear(); + if cx.reduce_motion() || !window.is_visible() { + // Nothing to see: the end state at once. + self.end_fade(window, cx); + } else { + // From where the veil is: a switch during a transition does not wait for it. + let now = cx.background_executor().now(); + let veil = self.veil(cx); + self.fade = Some(if self.shown_tab == tab { + Fade::uncovering(veil, now) + } else { + Fade::covering(veil, now) + }); + self.next_fade_frame(window, cx); + } + cx.notify(); + } + } + + /// Draws the screen of the tab chosen. + fn show_tab(&mut self, window: &mut Window, cx: &mut Context) { + if self.shown_tab == self.tab { + return; + } + self.shown_tab = self.tab; + // The home grid is no longer under the pointer. + self.release_home(cx); + // The screen arriving was not kept up to date while hidden, and is prepared only now: a + // switch undone under the veil prepares nothing. + self.refresh_table(cx); + if self.home_cards_stale { + self.prepare_home_cards(cx); + } + self.refresh_home(cx); + if self.shown_tab == Tab::Statistics { + // The home grid is not shown: its portraits are given back, and come back with the + // grid. + self.home_grid + .update(cx, |grid, cx| grid.release_images(window, cx)); + // Nor is the banner: its illustration too. + self.banner_art + .update(cx, |art, cx| art.release(window, cx)); + } + } + + /// Shows the end of the transition, if one runs, at once. + fn end_fade(&mut self, window: &mut Window, cx: &mut Context) { + self.fade = None; + if self.leave.is_some() { + self.finish_exit(window, cx); + } + self.show_tab(window, cx); + self.play_waiting(window, cx); + cx.notify(); + } + + /// Asks for the transition's next frame, once. + fn next_fade_frame(&mut self, window: &mut Window, cx: &mut Context) { + 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.frame_asked = false; + let Some(fade) = &self.fade else { + return; + }; + let now = cx.background_executor().now(); + if fade.finished(now) { + match fade.phase() { + FadePhase::Out => { + self.show_tab(window, cx); + // The champ select that ended leaves under the full veil: the home comes + // out of it, as after a switch of tabs. + if self.leave.is_some() { + self.finish_exit(window, cx); + } + self.fade = Some(Fade::uncovering(1., now)); + } + FadePhase::In => return self.end_fade(window, cx), + } + } + self.next_fade_frame(window, cx); + cx.notify(); + } +} diff --git a/crates/app/src/page/cards.rs b/crates/app/src/page/cards.rs index 5474dcb..662836d 100644 --- a/crates/app/src/page/cards.rs +++ b/crates/app/src/page/cards.rs @@ -1,22 +1,11 @@ -use super::{ChampionSortChosen, Page, Tab, home}; +use super::{ChampionSortChosen, Page, Tab}; use crate::card::Card; -use crate::card_grid::CardGrid; use crate::card_order::card_order; -use arena_tracker_core::{ChampSelect, ChampionRow, ChampionSearch, ChampionSort, StateFilter}; +use arena_tracker_core::{ChampionRow, ChampionSearch, ChampionSort, StateFilter}; 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) { - let replaced = self.others_grid.entity_id(); - self.others_grid = cx.new(|_| CardGrid::new()); - self.others_hover = Self::light_on_hover(&self.others_grid, cx); - self.lifts.drop_grid(replaced); - self.light(replaced, None, cx); - } - /// Computes the cards' order again: for when the home statistics (the champ select's during /// a champ select) or the sort change, and for nothing else. pub(super) fn reorder(&mut self) { @@ -67,7 +56,7 @@ impl Page { /// The home statistics' rows in the cards' order: the single iteration the home grid, the /// Anvil champions and « Autres champions » all follow. - fn ordered_rows(&self) -> impl Iterator { + pub(super) fn ordered_rows(&self) -> impl Iterator { let rows = self .home_statistics() .map_or(&[][..], |s| s.rows.as_slice()); @@ -105,130 +94,6 @@ impl Page { .update(cx, |grid, cx| grid.set_cards(cards, cx)); } - pub(super) fn in_champ_select(&self) -> bool { - self.champ_select.is_some() - } - - pub(super) 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(super) fn prepare_champ_select(&mut self, cx: &mut Context) { - // The same rows in the same order as the home grid (`ordered_rows`): the - // cards keep their place whatever the champ select does. 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 cards = self.champ_select_cards( - self.ordered_rows() - .filter(|row| ids.contains(&row.champion.id)), - ); - // A list the client did not send dims no tick: the ring would look empty. - self.ring.update(cx, |ring, cx| ring.set_anvil(anvil, cx)); - if champ_select.is_some() { - let remaining_pickable = cards.iter().filter(|card| !card.greyed()); - let first = remaining_pickable.clone().next().or_else(|| cards.first()); - let splash = first - .and_then(|card| self.champ_select_splashes.get(&card.id)) - .cloned(); - self.banner = home::BannerContent::champ_select( - self.home_season.as_ref(), - self.home_statistics(), - anvil.is_some(), - remaining_pickable.count(), - splash, - ); - self.select_art(self.ring.read(cx).lit(), 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) -> 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 { - 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) { - 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(super) fn refresh_others(&mut self, cx: &mut Context) { - if !self.others_open { - return; - } - let shown: Vec = 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(super) fn toggle_others(&mut self, cx: &mut Context) { - 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(super) fn fold_others(&mut self, window: &mut Window, cx: &mut Context) { - 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)); - } - /// 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(super) fn reset_home_view(&mut self, window: &mut Window, cx: &mut Context) { diff --git a/crates/app/src/page/champ_select/cards.rs b/crates/app/src/page/champ_select/cards.rs new file mode 100644 index 0000000..15576bd --- /dev/null +++ b/crates/app/src/page/champ_select/cards.rs @@ -0,0 +1,142 @@ +use super::super::{Page, home}; +use crate::card::Card; +use crate::card_grid::CardGrid; +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) { + let replaced = self.others_grid.entity_id(); + self.others_grid = cx.new(|_| CardGrid::new()); + self.others_hover = Self::light_on_hover(&self.others_grid, cx); + self.lifts.drop_grid(replaced); + self.light(replaced, None, cx); + } + + 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) { + // The same rows in the same order as the home grid (`ordered_rows`): the + // cards keep their place whatever the champ select does. 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 cards = self.champ_select_cards( + self.ordered_rows() + .filter(|row| ids.contains(&row.champion.id)), + ); + // A list the client did not send dims no tick: the ring would look empty. + self.ring.update(cx, |ring, cx| ring.set_anvil(anvil, cx)); + if champ_select.is_some() { + let remaining_pickable = cards.iter().filter(|card| !card.greyed()); + let first = remaining_pickable.clone().next().or_else(|| cards.first()); + let splash = first + .and_then(|card| self.champ_select_splashes.get(&card.id)) + .cloned(); + self.banner = home::BannerContent::champ_select( + self.home_season.as_ref(), + self.home_statistics(), + anvil.is_some(), + remaining_pickable.count(), + splash, + ); + self.select_art(self.ring.read(cx).lit(), 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) -> 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 { + 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) { + 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) { + if !self.others_open { + return; + } + let shown: Vec = 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.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) { + 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)); + } +} diff --git a/crates/app/src/page/champ_select/mod.rs b/crates/app/src/page/champ_select/mod.rs new file mode 100644 index 0000000..3844e21 --- /dev/null +++ b/crates/app/src/page/champ_select/mod.rs @@ -0,0 +1,95 @@ +use super::{ChampSelectTransition, Page, Tab}; +use crate::worker::LiveChampSelect; +use arena_tracker_core::{account_riot_id, same_riot_id}; +use gpui_kit::*; + +pub(super) 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 live champ select. Resolved when the signed-in Riot ID changes (or the + /// Accounts do), so preparing statistics builds no Riot ID per Account every time. + pub(in crate::page) fn champ_select_account(&mut self) -> Option { + let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?; + if self.champ_select_riot_id.as_deref() != Some(id) { + self.champ_select_riot_id = Some(id.into()); + self.champ_select_account = self + .accounts + .iter() + .find(|a| same_riot_id(&account_riot_id(a), id)) + .map(|a| a.puuid.clone()); + } + self.champ_select_account.clone() + } + + /// 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, + ) { + 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); + self.champ_select = champ_select; + if changed_page { + if self.in_champ_select() { + // The champ select is about the Challenge, whatever tab was open. + self.tab = Tab::Challenge; + // Nothing plays during a champ select: what waited is no longer news. + self.stop_holding(); + self.end_match(cx); + self.end_fade(window, cx); + // The home grid gives way to the champ select's sections. + self.home_grid + .update(cx, |grid, cx| grid.release_images(window, cx)); + // Its entry plays once the window shows it (#63 reveals it without focus). + self.entry_waiting = true; + } else { + 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(); + } + } + if switch { + // The Account belongs to the signed-in Riot ID: resolve it once, not on every + // statistics preparation. + self.champ_select_riot_id = None; + self.stats_generation += 1; + self.stats = None; + self.stats_error = None; + self.forget_home(); + self.stored = None; + self.reorder(); + // A new champ select starts with « Autres champions » folded and searchless. + self.fold_others(window, cx); + self.reload_in_background(window, cx); + // Nor does the banner keep the previous scope's Challenge while the new one + // loads: its Season, its ticks and its splash go with the statistics. + self.prepare_banner(cx); + } + if 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); + } +} diff --git a/crates/app/src/page/stage_motion.rs b/crates/app/src/page/champ_select/motion.rs similarity index 87% rename from crates/app/src/page/stage_motion.rs rename to crates/app/src/page/champ_select/motion.rs index 68e4313..ffdd5f7 100644 --- a/crates/app/src/page/stage_motion.rs +++ b/crates/app/src/page/champ_select/motion.rs @@ -1,4 +1,4 @@ -use super::Page; +use super::super::Page; use crate::card::{Card, Reason}; use crate::card_grid::CardGrid; use crate::motion::Fade; @@ -10,14 +10,14 @@ use std::time::Instant; impl Page { /// 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(super) fn may_animate(&self, window: &Window, cx: &App) -> bool { + 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(super) fn start_entry(&mut self, window: &Window, cx: &mut Context) { + pub(in crate::page) fn start_entry(&mut self, window: &Window, cx: &mut Context) { if !self.entry_waiting || !self.in_champ_select() { return; } @@ -40,14 +40,14 @@ impl Page { /// 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(super) fn end_stage(&mut self, cx: &mut Context) { + pub(in crate::page) fn end_stage(&mut self, cx: &mut Context) { 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(super) fn forget_stage(&mut self) { + pub(in crate::page) fn forget_stage(&mut self) { self.entry = None; self.entry_waiting = false; self.taken.clear(); @@ -56,7 +56,7 @@ impl Page { /// 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(super) fn start_exit(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn start_exit(&mut self, window: &mut Window, cx: &mut Context) { let now = cx.background_executor().now(); let hand = self.anvil_grid.entity_id(); let lifted: Vec<_> = self.lifts.lifted(hand, now).collect(); @@ -84,14 +84,19 @@ impl Page { /// Applies the end of the champ select that was leaving: the home comes back as #74 leaves /// it. - pub(super) fn finish_exit(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn finish_exit(&mut self, window: &mut Window, cx: &mut Context) { 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(super) fn lower_taken(&mut self, before: &[Card], window: &Window, cx: &mut Context) { + pub(in crate::page) fn lower_taken( + &mut self, + before: &[Card], + window: &Window, + cx: &mut Context, + ) { if !self.may_animate(window, cx) { return; } @@ -114,7 +119,13 @@ impl Page { } /// Whether card `id` of `grid` is the hand's and still on its way there at `now`. - pub(super) fn dealing(&self, grid: &Entity, id: u32, now: Instant, cx: &App) -> bool { + pub(in crate::page) fn dealing( + &self, + grid: &Entity, + id: u32, + now: Instant, + cx: &App, + ) -> bool { if grid.entity_id() != self.anvil_grid.entity_id() { return false; } @@ -153,7 +164,7 @@ impl Page { /// 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(super) fn stage_moving(&self, cx: &App) -> bool { + pub(in crate::page) fn stage_moving(&self, cx: &App) -> bool { if !self.taken.is_empty() || self.hover_waiting.is_some() { return true; } @@ -165,7 +176,11 @@ impl Page { } /// Asks for the champ select's next frame, once. - pub(super) fn next_stage_frame(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn next_stage_frame( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { if !self.stage_frame_asked { self.stage_frame_asked = true; cx.on_next_frame(window, |page, _, cx| page.stage_frame(cx)); @@ -187,7 +202,7 @@ impl Page { } /// The hand's cards moving over its grid, if any. - pub(super) fn hand_layer(&self, cx: &App) -> Option { + pub(in crate::page) fn hand_layer(&self, cx: &App) -> Option { // 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() { @@ -213,7 +228,7 @@ impl Page { } /// The title's opacity and how far below its place it is, while the entry brings it in. - pub(super) fn title_pose(&self, cx: &App) -> Option<(f32, f32)> { + 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())) } diff --git a/crates/app/src/page/champ_select/render.rs b/crates/app/src/page/champ_select/render.rs new file mode 100644 index 0000000..6f5fe3c --- /dev/null +++ b/crates/app/src/page/champ_select/render.rs @@ -0,0 +1,175 @@ +use super::super::{ + Page, + home::{StatsNotice, count_badge, notice_line}, +}; +use super::UNKNOWN_ANVIL; +use crate::card_grid::row_height; +use crate::theme::heading; +use gpui_kit::base::Button as BaseButton; +use gpui_kit::component::input::Input; +use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +impl Page { + /// 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 { + 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, + ) -> 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() + .child( + div() + .h_flex() + .flex_wrap() + .items_center() + .justify_between() + .gap_x_3() + .gap_y_2() + .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)) + }), + ) + .child(self.sort_selector(cx)), + ) + .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).hand_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. `window_width` + /// gives the cards' size: the grid is never shorter than a whole row, and in a small window + /// the column scrolls instead. + pub(in crate::page) fn others_area( + &self, + window_width: Pixels, + cx: &mut Context, + ) -> 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() + .when(open, |section| section.flex_1()) + .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().child( + Input::new(&self.others_search_input) + .cleanable(true) + .w(px(260.)) + .min_w(px(150.)), + ), + ) + .child( + // Cached, as the home's grid: hovering elsewhere does not draw its + // cards again. Its size comes from this style. + self.others_grid.clone().cached( + StyleRefinement::default() + .w_full() + .flex_1() + .min_h(row_height(window_width)), + ), + ) + .children(self.lift_layer(&self.others_grid, cx)) + }) + } +} diff --git a/crates/app/src/page/display.rs b/crates/app/src/page/display.rs index c80ebd7..f0aef4f 100644 --- a/crates/app/src/page/display.rs +++ b/crates/app/src/page/display.rs @@ -4,7 +4,6 @@ use crate::text::{CLIENT_ABSENT, official_differs, sync_line}; #[cfg(test)] use arena_tracker_core::{ChampionSort, StateFilter}; use arena_tracker_core::{ProgressCheck, UpdateProblem}; -use gpui_kit::base::Button as BaseButton; use gpui_kit::component::alert::Alert; use gpui_kit::component::select::Select; use gpui_kit::component::{ActiveTheme as _, Sizable as _, StyledExt as _}; @@ -12,57 +11,8 @@ use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; impl Page { - /// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them. - pub(super) fn navigation(&self, cx: &mut Context) -> impl IntoElement { - let theme = cx.theme(); - let (ring, muted, active, active_foreground, hover, hover_foreground) = ( - theme.ring, - theme.tab_foreground, - theme.tab_active, - theme.tab_active_foreground, - theme.accent, - theme.accent_foreground, - ); - let tabs = [ - ("tab-challenge", "Défi", Tab::Challenge), - ("tab-statistics", "Statistiques", Tab::Statistics), - ]; - div() - .h_flex() - .gap_1() - .flex_shrink_0() - .children(tabs.map(|(id, label, tab)| { - let current = self.tab == tab; - // The champ select takes the window: « Statistiques » waits for its end. - let disabled = tab == Tab::Statistics && self.in_champ_select(); - BaseButton::new(id) - .disabled(disabled) - .px_3() - .py_1() - .rounded_md() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) - // Always bordered, so the focus ring does not shift the label. - .border_1() - .border_color(transparent_black()) - .focus_visible(|style| { - style.border_color(if current { active_foreground } else { ring }) - }) - .text_color(if current { active_foreground } else { muted }) - .when(current, |button| button.bg(active)) - .when(!current && !disabled, |button| { - button.hover(|style| style.bg(hover).text_color(hover_foreground)) - }) - .when(disabled, |button| button.opacity(0.5)) - .accessibility_label(label) - .debug_selector(|| id.into()) - .child(label) - .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx))) - })) - } - /// One line each, the most important first; the stored data stays visible under all. - pub(super) fn banners(&self) -> Vec { + pub(super) fn status_alerts(&self) -> Vec { let mut banners = Vec::new(); if let Some(problem) = &self.status.problem { let message = problem.message(); @@ -215,7 +165,7 @@ impl Render for Page { ) }) .when(shown("banners"), |page| { - page.child(div().v_flex().gap_1().children(self.banners())) + 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 diff --git a/crates/app/src/page/home.rs b/crates/app/src/page/home.rs index b362238..9d0a1de 100644 --- a/crates/app/src/page/home.rs +++ b/crates/app/src/page/home.rs @@ -1,12 +1,10 @@ //! The « Défi » tab, the home: the Challenge of one Season, and its champions. -use arena_tracker_core::StateFilter; -use gpui_kit::base::Button as BaseButton; +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::prelude::FluentBuilder as _; use gpui_kit::*; mod banner; @@ -15,7 +13,7 @@ mod content; pub(super) use content::{BannerContent, Line}; use super::{Page, shown}; -use crate::card_grid::{MAX_WIDTH, row_height}; +use crate::card_grid::MAX_WIDTH; use crate::theme::heading; /// The filters on offer, whatever the Season. @@ -25,7 +23,6 @@ pub(super) const FILTERS: [(&str, StateFilter); 3] = [ ("Validés", StateFilter::Completed), ]; -const UNKNOWN_ANVIL: &str = "Champions de l'Enclume non communiqués par le client"; pub(super) 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 @@ -54,13 +51,13 @@ impl StatsNotice { } /// Whether something else on the page already says it: the notice stays silent then. - fn said_elsewhere(self) -> bool { + pub(super) 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. -fn notice_line(selector: &'static str, text: SharedString, muted: Hsla) -> AnyElement { +pub(super) fn notice_line(selector: &'static str, text: SharedString, muted: Hsla) -> AnyElement { div() .text_sm() .text_color(muted) @@ -70,7 +67,7 @@ fn notice_line(selector: &'static str, text: SharedString, muted: Hsla) -> AnyEl } /// The small bordered count beside a heading. -fn count_badge(count: SharedString, muted: Hsla, border: Hsla) -> impl IntoElement { +pub(super) fn count_badge(count: SharedString, muted: Hsla, border: Hsla) -> impl IntoElement { div() .px(px(7.)) .py(px(2.)) @@ -83,6 +80,46 @@ fn count_badge(count: SharedString, muted: Hsla, border: Hsla) -> impl IntoEleme } impl Page { + /// Whether one Season is selected, rather than all of them: only a Season has a Challenge. + pub(super) 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(super) 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(super) fn stats_notice(&self) -> Option { + 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 the Account is the one signed in to the client, known by the + // follower's status; else it is the one viewed. + let no_account = if self.in_champ_select() { + self.status.updating.is_none() + } else { + self.viewed().is_none() + }; + Some(if no_account { + StatsNotice::NoAccount + } else { + StatsNotice::Loading + }) + } + /// Under the status messages: the banner, then the heading with the filters and /// search, and the cards. It holds no chart (#71): the cached charts row only belongs to the /// Statistics tab. Everything is one centred column, as wide as the mockup's. @@ -158,7 +195,7 @@ impl Page { /// The sort selector: a sort icon and the choice, « Maîtrise » or « A–Z ». It stays on the /// home and during a champ select, and applies to every section of cards. - fn sort_selector(&self, cx: &App) -> impl IntoElement { + pub(super) fn sort_selector(&self, cx: &App) -> impl IntoElement { let muted = cx.theme().muted_foreground; div() .h_flex() @@ -175,159 +212,6 @@ impl Page { ) } - /// 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(super) fn anvil_line(&self) -> Option { - 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. - fn anvil_area(&self, window_width: Pixels, cx: &mut Context) -> 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() - .child( - div() - .h_flex() - .flex_wrap() - .items_center() - .justify_between() - .gap_x_3() - .gap_y_2() - .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)) - }), - ) - .child(self.sort_selector(cx)), - ) - .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).hand_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(super) 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. `window_width` - /// gives the cards' size: the grid is never shorter than a whole row, and in a small window - /// the column scrolls instead. - fn others_area(&self, window_width: Pixels, cx: &mut Context) -> 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() - .when(open, |section| section.flex_1()) - .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().child( - Input::new(&self.others_search_input) - .cleanable(true) - .w(px(260.)) - .min_w(px(150.)), - ), - ) - .child( - // Cached, as the home's grid: hovering elsewhere does not draw its - // cards again. Its size comes from this style. - self.others_grid.clone().cached( - StyleRefinement::default() - .w_full() - .flex_1() - .min_h(row_height(window_width)), - ), - ) - .children(self.lift_layer(&self.others_grid, cx)) - }) - } - /// « 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) -> impl IntoElement { diff --git a/crates/app/src/page/home/banner.rs b/crates/app/src/page/home/banner.rs index a60f64f..5d686cd 100644 --- a/crates/app/src/page/home/banner.rs +++ b/crates/app/src/page/home/banner.rs @@ -2,10 +2,12 @@ use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; -use super::{Line, NO_SEASON, Page}; +use super::{BannerContent, Line, NO_SEASON, Page}; use crate::banner_art::BannerArt; use crate::motion::{COUNTER_ROLL, ease_out}; +use crate::ring::{self, Tick}; use crate::theme::{banner_band, gold_ink, heading}; +use std::rc::Rc; impl Page { /// The banner, on the home and during a champ select: the ring, then the Season, the @@ -354,3 +356,47 @@ impl Render for BannerArt { } } } + +impl Page { + /// The banner's text and the ring's ticks, for when the home statistics change. Neither + /// follows the Format, the filter, the search nor the sort. + pub(in crate::page) fn prepare_banner(&mut self, cx: &mut Context) { + let stats = self.home_statistics(); + let champ_select = self.in_champ_select(); + let splashes = stats + .filter(|_| champ_select) + .into_iter() + .flat_map(|s| &s.rows) + .filter_map(|row| Some((row.champion.id, Rc::new(row.splash.clone()?)))) + .collect(); + let ticks: Rc<[Tick]> = stats + .and_then(|s| { + Some(ring::ticks( + &s.rows, + &s.challenge.as_ref()?.completion_order, + )) + }) + .unwrap_or_default() + .into(); + if !champ_select { + self.banner = BannerContent::new(self.home_season.as_ref(), stats); + if !self.playback.active() { + self.banner_art + .update(cx, |art, cx| art.set_target(self.banner.splash.clone(), cx)); + } + } + self.champ_select_splashes = splashes; + self.ring.update(cx, |ring, cx| ring.set_ticks(ticks, cx)); + } +} + +impl Page { + pub(in crate::page) fn select_art(&self, hovered: Option, cx: &mut Context) { + let splash = match hovered { + Some(id) => self.champ_select_splashes.get(&id), + None => self.banner.splash.as_ref(), + }; + self.banner_art + .update(cx, |art, cx| art.set_target(splash.cloned(), cx)); + } +} diff --git a/crates/app/src/page/home/content.rs b/crates/app/src/page/home/content.rs index e18a377..a9a20c6 100644 --- a/crates/app/src/page/home/content.rs +++ b/crates/app/src/page/home/content.rs @@ -4,7 +4,7 @@ use std::rc::Rc; use arena_tracker_core::{MatchOutcome, Splash, Statistics}; use gpui_kit::SharedString; -use super::UNKNOWN_ANVIL; +use super::super::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. diff --git a/crates/app/src/page/hover.rs b/crates/app/src/page/hover.rs index c1b025a..ef34051 100644 --- a/crates/app/src/page/hover.rs +++ b/crates/app/src/page/hover.rs @@ -145,13 +145,4 @@ impl Page { self.select_art(id, cx); } } - - pub(super) fn select_art(&self, hovered: Option, cx: &mut Context) { - let splash = match hovered { - Some(id) => self.champ_select_splashes.get(&id), - None => self.banner.splash.as_ref(), - }; - self.banner_art - .update(cx, |art, cx| art.set_target(splash.cloned(), cx)); - } } diff --git a/crates/app/src/page/lifecycle.rs b/crates/app/src/page/lifecycle.rs new file mode 100644 index 0000000..1977fd6 --- /dev/null +++ b/crates/app/src/page/lifecycle.rs @@ -0,0 +1,45 @@ +use super::Page; +use crate::worker::spawn_refresh; +use gpui_kit::*; + +impl Page { + /// The follower thread was just started. + pub fn following(&mut self, cx: &mut Context) { + self.pending_round = true; + cx.notify(); + } + + /// The page gives way to another screen (« Paramètres »): what it shows is given back, the + /// grids' portraits and the banner's splash, in memory and in the window's atlas. They load + /// again when it is drawn. + pub fn hidden(&mut self, window: &mut Window, cx: &mut Context) { + 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)); + } + + /// The page is back in front of « Paramètres ». + pub fn uncovered(&mut self, window: &mut Window, cx: &mut Context) { + self.covered = false; + self.play_waiting(window, cx); + self.start_entry(window, cx); + } + + /// Starts a refresh, or queues one behind the refresh already running. + pub fn request_refresh(&mut self, cx: &mut Context) { + if self.refresh.request() { + spawn_refresh(self.tracker.clone(), self.tx.clone()); + } + cx.notify(); + } + + pub fn busy(&self) -> bool { + self.progress.is_some() || self.refresh.running() || self.pending_round + } +} diff --git a/crates/app/src/page/state.rs b/crates/app/src/page/state.rs deleted file mode 100644 index 1bdfea6..0000000 --- a/crates/app/src/page/state.rs +++ /dev/null @@ -1,140 +0,0 @@ -use super::{Page, Tab, home}; -use crate::worker::spawn_refresh; -use arena_tracker_core::{Account, ProgressCheck, SeasonScope, Statistics}; -use gpui_kit::*; - -impl Page { - /// The follower thread was just started. - pub fn following(&mut self, cx: &mut Context) { - self.pending_round = true; - cx.notify(); - } - - /// The page gives way to another screen (« Paramètres »): what it shows is given back, the - /// grids' portraits and the banner's splash, in memory and in the window's atlas. They load - /// again when it is drawn. - pub fn hidden(&mut self, window: &mut Window, cx: &mut Context) { - 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)); - } - - /// The page is back in front of « Paramètres ». - pub fn uncovered(&mut self, window: &mut Window, cx: &mut Context) { - self.covered = false; - self.play_waiting(window, cx); - self.start_entry(window, cx); - } - - /// Starts a refresh, or queues one behind the refresh already running. - pub fn request_refresh(&mut self, cx: &mut Context) { - if self.refresh.request() { - spawn_refresh(self.tracker.clone(), self.tx.clone()); - } - cx.notify(); - } - - pub fn busy(&self) -> bool { - self.progress.is_some() || self.refresh.running() || self.pending_round - } - - /// Whether one Season is selected, rather than all of them: only a Season has a Challenge. - pub(super) fn in_season(&self) -> bool { - matches!(self.season, SeasonScope::Season(_)) - } - - /// The Account shown: the pinned one, else the one being updated. - pub(super) 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 Account whose data the page shows: during a champ select the one signed in to the - /// client, whatever the pinned or followed one is, else `viewed`. - pub(super) fn displayed(&self) -> Option<&Account> { - if self.in_champ_select() { - let puuid = self.champ_select_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(super) 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(super) fn official(&self) -> Option<&ProgressCheck> { - let updated = matches!((self.displayed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid); - let shown = match (self.shown_tab, &self.season) { - (Tab::Challenge, _) => self.home_season.as_deref(), - (Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()), - (Tab::Statistics, SeasonScope::AllSeasons) => None, - }; - let current = shown.is_some() && shown == self.current_season.as_deref(); - (updated && current).then_some(&self.status.official_progress) - } - - /// What the home reads: its own statistics when its scope differs, else the Statistics tab's. - pub(super) 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(super) fn stats_notice(&self) -> Option { - use home::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 the Account is the one signed in to the client, known by the - // follower's status; else it is the one viewed. - let no_account = if self.in_champ_select() { - self.status.updating.is_none() - } else { - self.viewed().is_none() - }; - Some(if no_account { - StatsNotice::NoAccount - } else { - StatsNotice::Loading - }) - } - - /// The tab's own statistics error: the home may have computed its own. - pub(super) fn error(&self) -> Option<&String> { - match (self.shown_tab, &self.home_scope) { - (Tab::Challenge, Some(_)) => self.home_error.as_ref(), - _ => self.stats_error.as_ref(), - } - } -} diff --git a/crates/app/src/page/statistics.rs b/crates/app/src/page/statistics.rs index dc74f82..1b0cb8f 100644 --- a/crates/app/src/page/statistics.rs +++ b/crates/app/src/page/statistics.rs @@ -1,5 +1,7 @@ //! The « Statistiques » tab: the analysis of one Account, Season and Format. +mod data; + use arena_tracker_core::{ChallengeSummary, Charts, ProgressCheck, StateFilter}; use gpui_kit::component::chart::{AreaChart, BarChart}; use gpui_kit::component::input::Input; diff --git a/crates/app/src/page/data.rs b/crates/app/src/page/statistics/data.rs similarity index 78% rename from crates/app/src/page/data.rs rename to crates/app/src/page/statistics/data.rs index a0022fa..fb46f28 100644 --- a/crates/app/src/page/data.rs +++ b/crates/app/src/page/statistics/data.rs @@ -1,26 +1,81 @@ -use super::{ALL_FORMATS, AccountItem, NextHome, Page, home, now_ms}; +use super::super::{ALL_FORMATS, AccountItem, NextHome, Page, Tab, now_ms}; use crate::card::Card; -use crate::ring::{self, Tick}; use crate::worker::{compute_statistics, spawn_statistics}; use arena_tracker_core::{ - Scope, SeasonScope, StateFilter, Statistics, account_riot_id, same_riot_id, + Account, ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, account_riot_id, }; use gpui_kit::component::IndexPath; use gpui_kit::*; -use std::rc::Rc; use std::time::Instant; impl Page { + /// The Account shown: the pinned one, else the one being updated. + 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 Account whose data the page shows: during a champ select the one signed in to the + /// client, whatever the pinned or followed one is, else `viewed`. + pub(in crate::page) fn displayed(&self) -> Option<&Account> { + if self.in_champ_select() { + let puuid = self.champ_select_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.shown_tab, &self.season) { + (Tab::Challenge, _) => self.home_season.as_deref(), + (Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()), + (Tab::Statistics, SeasonScope::AllSeasons) => None, + }; + let 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> { + match (self.shown_tab, &self.home_scope) { + (Tab::Challenge, Some(_)) => self.home_error.as_ref(), + _ => self.stats_error.as_ref(), + } + } + /// 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(super) fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn reload_in_background( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { 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(super) fn reload(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn reload(&mut self, window: &mut Window, cx: &mut Context) { self.reload_accounts(window, cx); self.recompute(window, cx); } @@ -130,7 +185,10 @@ impl Page { } /// Keeps what was computed for the home's own scope, if it had one, and for which Account. - pub(super) fn set_home_result(&mut self, home: Option>>) { + pub(in crate::page) fn set_home_result( + &mut self, + home: Option>>, + ) { self.home_computed = home .as_ref() .and_then(|_| self.shown.clone().zip(self.home_scope.clone())); @@ -141,7 +199,7 @@ impl Page { }; } - pub(super) fn forget_home(&mut self) { + pub(in crate::page) fn forget_home(&mut self) { self.home_stats = None; self.home_error = None; self.home_computed = None; @@ -157,21 +215,6 @@ impl Page { } } - /// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the - /// Accounts do), so preparing statistics builds no Riot ID per Account every time. - fn champ_select_account(&mut self) -> Option { - let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?; - if self.champ_select_riot_id.as_deref() != Some(id) { - self.champ_select_riot_id = Some(id.into()); - self.champ_select_account = self - .accounts - .iter() - .find(|a| same_riot_id(&account_riot_id(a), id)) - .map(|a| a.puuid.clone()); - } - self.champ_select_account.clone() - } - fn statistics_scope(&self) -> Scope { if self.in_champ_select() && let Some(season) = &self.current_season @@ -189,7 +232,7 @@ impl Page { /// Requests the statistics from a worker (`start_job`: none is running), or shows none when no /// Account is viewed. - pub(super) fn recompute_in_background( + pub(in crate::page) fn recompute_in_background( &mut self, start_job: bool, window: &mut Window, @@ -224,7 +267,7 @@ impl Page { /// 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(super) fn recompute(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn recompute(&mut self, window: &mut Window, cx: &mut Context) { let viewed = self.prepare_statistics(true, window, cx); self.stats = None; self.stats_error = None; @@ -250,7 +293,7 @@ impl Page { } /// Shows `stats`: the Format choices, the charts and the table. - pub(super) fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) { + pub(in crate::page) fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) { if self.hold_grid { // Row indices are reusable only while the catalog has the same champions. let rows = self @@ -322,35 +365,4 @@ impl Page { self.play_waiting(window, cx); cx.notify(); } - - /// 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(super) fn prepare_banner(&mut self, cx: &mut Context) { - let stats = self.home_statistics(); - let champ_select = self.in_champ_select(); - let splashes = stats - .filter(|_| champ_select) - .into_iter() - .flat_map(|s| &s.rows) - .filter_map(|row| Some((row.champion.id, Rc::new(row.splash.clone()?)))) - .collect(); - let ticks: Rc<[Tick]> = stats - .and_then(|s| { - Some(ring::ticks( - &s.rows, - &s.challenge.as_ref()?.completion_order, - )) - }) - .unwrap_or_default() - .into(); - if !champ_select { - self.banner = home::BannerContent::new(self.home_season.as_ref(), stats); - if !self.playback.active() { - self.banner_art - .update(cx, |art, cx| art.set_target(self.banner.splash.clone(), cx)); - } - } - self.champ_select_splashes = splashes; - self.ring.update(cx, |ring, cx| ring.set_ticks(ticks, cx)); - } } diff --git a/crates/app/src/page/tabs.rs b/crates/app/src/page/tabs.rs deleted file mode 100644 index 1a47e2e..0000000 --- a/crates/app/src/page/tabs.rs +++ /dev/null @@ -1,103 +0,0 @@ -use super::{Page, Tab}; -use crate::motion::{Fade, FadePhase}; -use gpui_kit::*; - -impl Page { - pub(super) fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context) { - // The champ select takes the window: the Statistics tab waits for its end. - if tab == Tab::Statistics && self.in_champ_select() { - return; - } - if self.tab != tab { - self.tab = tab; - // The grids leave under the veil: no card stays lifted over it. - self.lifts.clear(); - if cx.reduce_motion() || !window.is_visible() { - // Nothing to see: the end state at once. - self.end_fade(window, cx); - } else { - // From where the veil is: a switch during a transition does not wait for it. - let now = cx.background_executor().now(); - let veil = self.veil(cx); - self.fade = Some(if self.shown_tab == tab { - Fade::uncovering(veil, now) - } else { - Fade::covering(veil, now) - }); - self.next_fade_frame(window, cx); - } - cx.notify(); - } - } - - /// Draws the screen of the tab chosen. - fn show_tab(&mut self, window: &mut Window, cx: &mut Context) { - if self.shown_tab == self.tab { - return; - } - self.shown_tab = self.tab; - // The home grid is no longer under the pointer. - self.release_home(cx); - // The screen arriving was not kept up to date while hidden, and is prepared only now: a - // switch undone under the veil prepares nothing. - self.refresh_table(cx); - if self.home_cards_stale { - self.prepare_home_cards(cx); - } - self.refresh_home(cx); - if self.shown_tab == Tab::Statistics { - // The home grid is not shown: its portraits are given back, and come back with the - // grid. - self.home_grid - .update(cx, |grid, cx| grid.release_images(window, cx)); - // Nor is the banner: its illustration too. - self.banner_art - .update(cx, |art, cx| art.release(window, cx)); - } - } - - /// 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.fade = None; - if self.leave.is_some() { - self.finish_exit(window, cx); - } - self.show_tab(window, cx); - self.play_waiting(window, cx); - cx.notify(); - } - - /// Asks for the transition's next frame, once. - pub(super) fn next_fade_frame(&mut self, window: &mut Window, cx: &mut Context) { - 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.frame_asked = false; - let Some(fade) = &self.fade else { - return; - }; - let now = cx.background_executor().now(); - if fade.finished(now) { - match fade.phase() { - FadePhase::Out => { - self.show_tab(window, cx); - // The champ select that ended leaves under the full veil: the home comes - // out of it, as after a switch of tabs. - if self.leave.is_some() { - self.finish_exit(window, cx); - } - self.fade = Some(Fade::uncovering(1., now)); - } - FadePhase::In => return self.end_fade(window, cx), - } - } - self.next_fade_frame(window, cx); - cx.notify(); - } -} diff --git a/crates/app/src/page/tests.rs b/crates/app/src/page/tests.rs index 4876ece..dc36a91 100644 --- a/crates/app/src/page/tests.rs +++ b/crates/app/src/page/tests.rs @@ -1,77 +1,18 @@ -use std::cell::{Cell, RefCell}; - -use std::path::Path; - -use std::rc::Rc; - -use std::sync::Arc; - -use std::time::Duration; - -use arena_tracker_core::{ - Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort, - ChampionState, Charts, Date, FollowedMatch, Format, MatchHistorySource, RiotApi, Season, - SeasonScope, SourceError, StateFilter, Statistics, Status, Tracker, -}; - -use gpui_kit::base::async_util::unbounded; - -use gpui_kit::{ - AppContext, Bounds, Entity, Focusable, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, - ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, WindowBounds, WindowOptions, - WindowVisibility, point, px, size, -}; - -use super::{ChampionSortChosen, Page, SelectEvent, Tab}; - -use crate::card::ASPECT; - -use crate::card_grid::{CardGrid, row_height}; - -use crate::champion_table::tests::row; - -use crate::motion::MatchEnd; - -// The Arena champ select of #13, replayed into the page (#74). The capture is the one the -// core replays: local cell 16, ally 17; the Anvil champions are 233, 64, 5, 16 and 68 and -// the client only offers 103, 12, 16, 233, 25 and 50. -use arena_tracker_core::{ - ChampSelect, ChampSelectReader, ChampionCatalog, ChampionSource, ClientError, -}; - -use serde_json::{Value, json}; - -use crate::card::{Card, Reason}; - -// The tall card portraits (#77). -use std::path::PathBuf; - -use crate::card_images::tests::{PORTRAIT_JPEG, TestDir}; - -// ---- The banner and its ring (#84). ---- - -use arena_tracker_core::{LastMatch, MatchOutcome, Splash, SplashFocus}; - -use crate::ring::Tick; - -mod fixtures; -use fixtures::*; -mod champ_select_fixtures; -use champ_select_fixtures::*; -mod presentation_fixtures; -use presentation_fixtures::*; - mod account; mod banner; +mod banner_fixtures; mod banner_scope; mod card_sheet; mod champ_select_browsing; mod champ_select_capture; +mod champ_select_fixtures; mod champ_select_motion; mod champ_select_others; mod grid; mod home; mod match_animation; mod navigation; +mod page_fixtures; mod portraits; mod sorting; +mod sorting_fixtures; diff --git a/crates/app/src/page/tests/account.rs b/crates/app/src/page/tests/account.rs index 3de11d5..45d9e90 100644 --- a/crates/app/src/page/tests/account.rs +++ b/crates/app/src/page/tests/account.rs @@ -1,4 +1,16 @@ -use super::*; +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) { @@ -94,7 +106,7 @@ fn only_entering_a_champ_select_is_reported_as_an_entry(cx: &mut TestAppContext) let entered = entered.clone(); cx.subscribe( &page, - move |_, transition: &super::super::ChampSelectTransition, _| { + move |_, transition: &crate::page::ChampSelectTransition, _| { entered.borrow_mut().push(transition.entered) }, ) diff --git a/crates/app/src/page/tests/banner.rs b/crates/app/src/page/tests/banner.rs index e2a16e4..4adc26f 100644 --- a/crates/app/src/page/tests/banner.rs +++ b/crates/app/src/page/tests/banner.rs @@ -1,4 +1,23 @@ -use super::*; +use super::banner_fixtures::{ + banner, banner_champion, banner_rows, banner_statistics, bold, draw_loaded, held_splashes, + in_atlas, loaded_splashes, on, ring_renders, ring_ticks, rows_with_splashes, splash, +}; + +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) { diff --git a/crates/app/src/page/tests/presentation_fixtures.rs b/crates/app/src/page/tests/banner_fixtures.rs similarity index 63% rename from crates/app/src/page/tests/presentation_fixtures.rs rename to crates/app/src/page/tests/banner_fixtures.rs index 1b02147..adf58c8 100644 --- a/crates/app/src/page/tests/presentation_fixtures.rs +++ b/crates/app/src/page/tests/banner_fixtures.rs @@ -1,68 +1,15 @@ -use super::*; - -// The sort of the cards (#76). - -/// A row with a name, an id and its Mastery Points. -pub(super) fn with_points(id: u32, name: &str, points: Option) -> ChampionRow { - ChampionRow { - champion: Champion { - id, - key: name.into(), - name: name.into(), - }, - state: Some(ChampionState::NeverPlayed), - challenge: Some(ChampionChallenge::default()), - mastery_points: points, - ..row(name) - } -} - -/// A to Z, as the statistics give them. -pub(super) fn rows_with_points() -> Vec { - vec![ - with_points(1, "Ahri", None), - with_points(2, "Brand", Some(500)), - with_points(3, "Garen", Some(9_000)), - with_points(4, "Jinx", Some(500)), - with_points(5, "Lux", Some(0)), - with_points(6, "Zed", None), - ] -} - -pub(super) const BY_MASTERY: [&str; 6] = ["Garen", "Brand", "Jinx", "Lux", "Ahri", "Zed"]; - -pub(super) const A_TO_Z: [&str; 6] = ["Ahri", "Brand", "Garen", "Jinx", "Lux", "Zed"]; - -/// The sorts the page reports, in order. -pub(super) fn record_sorts( - page: &Entity, - cx: &mut VisualTestContext, -) -> Rc>> { - let chosen = Rc::new(RefCell::new(Vec::new())); - let events = chosen.clone(); - cx.update(|_, cx| { - cx.subscribe(page, move |_, event: &ChampionSortChosen, _| { - events.borrow_mut().push(event.0) - }) - .detach() - }); - chosen -} - -/// The player picks `label` in the sort selector. -pub(super) fn pick_sort(page: &Entity, cx: &mut VisualTestContext, label: &'static str) { - let select = page.read_with(cx, |p, _| p.sort_select.clone()); - cx.update(|_, cx| { - select.update(cx, |_, cx| { - cx.emit(SelectEvent::Confirm(Some(label.into()))) - }) - }); - draw(cx); -} - -pub(super) fn reorders(page: &Entity, cx: &mut VisualTestContext) -> usize { - page.read_with(cx, |p, _| p.reorders) -} +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, 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 { @@ -128,11 +75,11 @@ pub(super) fn banner_statistics( pub(super) fn banner( page: &Entity, cx: &mut VisualTestContext, -) -> super::super::home::BannerContent { +) -> crate::page::home::BannerContent { page.read_with(cx, |page, _| page.banner.clone()) } -pub(super) fn bold(line: &super::super::home::Line) -> &str { +pub(super) fn bold(line: &crate::page::home::Line) -> &str { &line.text[line.bold.clone()] } diff --git a/crates/app/src/page/tests/banner_scope.rs b/crates/app/src/page/tests/banner_scope.rs index 76c9f26..c97aa92 100644 --- a/crates/app/src/page/tests/banner_scope.rs +++ b/crates/app/src/page/tests/banner_scope.rs @@ -1,4 +1,17 @@ -use super::*; +use super::banner_fixtures::{ + banner, banner_statistics, draw_loaded, held_splashes, in_atlas, 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( diff --git a/crates/app/src/page/tests/card_sheet.rs b/crates/app/src/page/tests/card_sheet.rs index afc5290..fe31af6 100644 --- a/crates/app/src/page/tests/card_sheet.rs +++ b/crates/app/src/page/tests/card_sheet.rs @@ -1,4 +1,9 @@ -use super::*; +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) { diff --git a/crates/app/src/page/tests/champ_select_browsing.rs b/crates/app/src/page/tests/champ_select_browsing.rs index 7e630d1..2b997a9 100644 --- a/crates/app/src/page/tests/champ_select_browsing.rs +++ b/crates/app/src/page/tests/champ_select_browsing.rs @@ -1,4 +1,18 @@ -use super::*; +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 @@ -190,7 +204,7 @@ fn no_champ_select_changes_nothing(cx: &mut TestAppContext) { let entered = entered.clone(); cx.subscribe( &page, - move |_, transition: &super::super::ChampSelectTransition, _| { + move |_, transition: &crate::page::ChampSelectTransition, _| { entered.borrow_mut().push(transition.entered) }, ) diff --git a/crates/app/src/page/tests/champ_select_capture.rs b/crates/app/src/page/tests/champ_select_capture.rs index 451c9fa..d86ebdd 100644 --- a/crates/app/src/page/tests/champ_select_capture.rs +++ b/crates/app/src/page/tests/champ_select_capture.rs @@ -1,4 +1,16 @@ -use super::*; +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, switch_tab}; +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) { @@ -330,7 +342,7 @@ async fn missing_statistics_are_said_once_and_leave_nothing_to_browse(cx: &mut T page.read_with(&window, |p, _| { assert_eq!( p.stats_notice(), - Some(super::super::home::StatsNotice::NoSeason) + Some(crate::page::home::StatsNotice::NoSeason) ); }); assert!(window.debug_bounds("no-season").is_some()); diff --git a/crates/app/src/page/tests/champ_select_fixtures.rs b/crates/app/src/page/tests/champ_select_fixtures.rs index 5101b35..6678b8a 100644 --- a/crates/app/src/page/tests/champ_select_fixtures.rs +++ b/crates/app/src/page/tests/champ_select_fixtures.rs @@ -1,4 +1,17 @@ -use super::*; +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"; @@ -55,9 +68,7 @@ impl MatchHistorySource for JoueurHistory { "EUW1_2" => (233, "Briar", 4), _ => return Err(SourceError::NotFound), }; - let raw = - include_str!("../../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json") - .replace("fixture-puuid-self", "Joueur"); + 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() { diff --git a/crates/app/src/page/tests/champ_select_motion.rs b/crates/app/src/page/tests/champ_select_motion.rs index 7c87de6..b5fba56 100644 --- a/crates/app/src/page/tests/champ_select_motion.rs +++ b/crates/app/src/page/tests/champ_select_motion.rs @@ -1,4 +1,19 @@ -use super::*; +use super::champ_select_fixtures::{ + ANVIL_A_TO_Z, anvil_cards, below, bounds, click_others, computed, entering, finish_motion, + frames, ids, joueur_tracker, leave, page_in_champ_select, reasons, scroll_champ_select_down, + send, start_leaving, with_bans_and_ally, +}; +use super::page_fixtures::{ + animations, assert_at_rest, draw, focus_sort, frame_after, hover, open_page_with_tracker, + press, rise, settle, shown_tab, switch_tab, veil, +}; +use crate::card::Reason; +use crate::page::Tab; +use arena_tracker_core::StateFilter; +use gpui_kit::{ + Bounds, Modifiers, TestAppContext, VisualTestContext, WindowVisibility, point, px, size, +}; +use std::time::Duration; // #87 on the Arena capture, step by step: the band of light and the title at once, then // the Anvil champions (A to Z: Briar, Lee Sin, Rumble, Soraka, Xin Zhao) from the bottom of diff --git a/crates/app/src/page/tests/champ_select_others.rs b/crates/app/src/page/tests/champ_select_others.rs index 13d686e..c92769c 100644 --- a/crates/app/src/page/tests/champ_select_others.rs +++ b/crates/app/src/page/tests/champ_select_others.rs @@ -1,4 +1,13 @@ -use super::*; +use super::champ_select_fixtures::{ + OTHERS_A_TO_Z, activate, anvil_cards, capture, click_others, focus_others_toggle, frames, ids, + others_cards, others_open, page_in_champ_select, read_champ_select, reasons, + scroll_champ_select_down, send, with_bans_and_ally, +}; +use super::page_fixtures::{draw, hover, rise, settle}; +use crate::card::Reason; +use crate::card_grid::CardGrid; +use arena_tracker_core::ChampSelectReader; +use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext, point, px}; #[gpui::test] async fn others_is_folded_at_entry_and_builds_no_card(cx: &mut TestAppContext) { diff --git a/crates/app/src/page/tests/grid.rs b/crates/app/src/page/tests/grid.rs index ec5ec3f..e985a56 100644 --- a/crates/app/src/page/tests/grid.rs +++ b/crates/app/src/page/tests/grid.rs @@ -1,4 +1,14 @@ -use super::*; +use super::page_fixtures::{ + center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show, + statistics, switch_tab, +}; +use crate::card::ASPECT; +use crate::champion_table::tests::row; +use crate::page::Tab; +use arena_tracker_core::{ + Champion, ChampionChallenge, ChampionRow, ChampionState, Date, StateFilter, +}; +use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px}; #[gpui::test] fn the_grid_follows_the_alias_search_and_the_filters(cx: &mut TestAppContext) { diff --git a/crates/app/src/page/tests/home.rs b/crates/app/src/page/tests/home.rs index fea6897..b2dff3d 100644 --- a/crates/app/src/page/tests/home.rs +++ b/crates/app/src/page/tests/home.rs @@ -1,4 +1,14 @@ -use super::*; +use super::banner_fixtures::banner; +use super::champ_select_fixtures::joueur_tracker; +use super::page_fixtures::{ + RefreshHistory, assert_home_says, champions, draw, grid_names, open_page, open_page_in_season, + open_page_with_tracker, season, show, statistics, switch_tab, +}; +use crate::champion_table::tests::row; +use crate::page::{Page, Tab}; +use arena_tracker_core::{ChampionRow, ChampionState, Format, SeasonScope, StateFilter, Tracker}; +use gpui_kit::{TestAppContext, VisualTestContext}; +use std::path::Path; #[gpui::test] fn the_app_opens_on_the_challenge_with_all_champions_selected(cx: &mut TestAppContext) { @@ -7,7 +17,7 @@ fn the_app_opens_on_the_challenge_with_all_champions_selected(cx: &mut TestAppCo page.read_with(cx, |page, _| { assert_eq!(page.tab, Tab::Challenge); assert_eq!(page.home_filter, StateFilter::All); - assert_eq!(super::super::home::FILTERS[0].0, "Tous"); + assert_eq!(crate::page::home::FILTERS[0].0, "Tous"); assert_eq!(page.home_season.as_deref(), Some("Saison")); }); } @@ -30,7 +40,7 @@ fn without_a_current_season_the_home_has_no_challenge(cx: &mut TestAppContext) { #[gpui::test] fn the_home_says_why_it_has_no_cards_until_the_statistics_arrive(cx: &mut TestAppContext) { - use super::super::home::StatsNotice; + use crate::page::home::StatsNotice; // A Season but no Account at all. let (page, cx) = open_page_in_season(cx); let cx = &mut { cx }; @@ -56,7 +66,7 @@ fn the_home_says_why_it_has_no_cards_until_the_statistics_arrive(cx: &mut TestAp #[gpui::test] async fn the_home_says_the_statistics_are_loading(cx: &mut TestAppContext) { - use super::super::home::StatsNotice; + use crate::page::home::StatsNotice; cx.executor().allow_parking(); let (page, mut window) = open_page_with_tracker(cx, joueur_tracker()); cx.condition(&page, |p, _| p.stats.is_some()).await; diff --git a/crates/app/src/page/tests/match_animation.rs b/crates/app/src/page/tests/match_animation.rs index bf04dd0..94f498a 100644 --- a/crates/app/src/page/tests/match_animation.rs +++ b/crates/app/src/page/tests/match_animation.rs @@ -1,4 +1,18 @@ -use super::*; +use super::banner_fixtures::{ + banner_champion, banner_rows, banner_statistics, on, rows_with_splashes, +}; +use super::page_fixtures::{ + animate, animations, assert_at_rest, champions, draw, frame_after, home_names, hover, + open_page_in_season, played, round_with_matches, settle, show, shown_tab, start_switch, + statistics, statistics_arrive, switch_tab, until_landed, +}; + +use crate::card_images::tests::TestDir; +use crate::motion::MatchEnd; +use crate::page::Tab; +use arena_tracker_core::{ChampionRow, LastMatch, MatchOutcome, StateFilter}; +use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, WindowVisibility, point, px}; +use std::rc::Rc; #[gpui::test] fn an_animation_waits_for_the_challenge_to_show_and_only_the_strongest_plays( diff --git a/crates/app/src/page/tests/navigation.rs b/crates/app/src/page/tests/navigation.rs index edf3da5..a86b658 100644 --- a/crates/app/src/page/tests/navigation.rs +++ b/crates/app/src/page/tests/navigation.rs @@ -1,4 +1,12 @@ -use super::*; +use super::page_fixtures::{ + animations, assert_at_rest, center, champions, draw, frame_after, open_page, + open_page_in_season, show, shown_tab, start_switch, statistics, switch_tab, veil, +}; +use crate::page::Tab; +use gpui_kit::{ + KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext, VisualTestContext, + WindowVisibility, +}; #[gpui::test] fn the_navigation_switches_tabs_with_the_mouse(cx: &mut TestAppContext) { diff --git a/crates/app/src/page/tests/fixtures.rs b/crates/app/src/page/tests/page_fixtures.rs similarity index 93% rename from crates/app/src/page/tests/fixtures.rs rename to crates/app/src/page/tests/page_fixtures.rs index 5705dca..15023b7 100644 --- a/crates/app/src/page/tests/fixtures.rs +++ b/crates/app/src/page/tests/page_fixtures.rs @@ -1,4 +1,25 @@ -use super::*; +use crate::card_grid::CardGrid; +use crate::champion_table::tests::row; +use crate::motion::MatchEnd; +use crate::page::{Page, Tab}; +use arena_tracker_core::{ + Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort, + ChampionState, Charts, Date, FollowedMatch, Format, MatchHistorySource, RiotApi, Season, + SourceError, Statistics, Status, Tracker, +}; +use gpui_kit::base::async_util::unbounded; +use gpui_kit::{ + AppContext, Bounds, Entity, Focusable, Modifiers, TestAppContext, VisualTestContext, + WindowBounds, WindowOptions, point, px, size, +}; +use std::cell::Cell; +use std::path::Path; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Duration; + +pub(super) const MATCH_1750: &str = + include_str!("../../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json"); /// Switches to a tab, and lets its transition end. pub(super) fn switch_tab(page: &Entity, cx: &mut VisualTestContext, tab: Tab) { @@ -54,7 +75,7 @@ pub(super) fn open_page_with_sort( cx.new(|cx| { Page::new( tracker, - super::super::Launch { + crate::page::Launch { notice: None, following: false, champion_sort, @@ -98,10 +119,7 @@ impl MatchHistorySource for RefreshHistory { } fn fetch_match(&self, _: &str) -> Result { - Ok( - include_str!("../../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json") - .replace("fixture-puuid-self", "Alice"), - ) + Ok(MATCH_1750.replace("fixture-puuid-self", "Alice")) } } @@ -191,12 +209,12 @@ pub(super) fn show(page: &Entity, cx: &mut VisualTestContext, stats: Stati /// above a grid that says none matches. pub(super) fn assert_home_says( window: &mut VisualTestContext, - notice: super::super::home::StatsNotice, + notice: crate::page::home::StatsNotice, ) { draw(window); assert_eq!( window.debug_bounds("home-notice").is_some(), - !matches!(notice, super::super::home::StatsNotice::Error) + !matches!(notice, crate::page::home::StatsNotice::Error) ); assert!(window.debug_bounds("home-tools").is_none()); assert!(window.debug_bounds("card-list").is_none()); diff --git a/crates/app/src/page/tests/portraits.rs b/crates/app/src/page/tests/portraits.rs index 8177e64..c573f2a 100644 --- a/crates/app/src/page/tests/portraits.rs +++ b/crates/app/src/page/tests/portraits.rs @@ -1,4 +1,14 @@ -use super::*; +use super::champ_select_fixtures::{ + ANVIL, OTHERS_A_TO_Z, card_portrait, click_others, frames, ids, joueur_tracker, leave, + others_cards, others_open, page_in_champ_select, send, tracker_with_portraits, +}; +use super::page_fixtures::{draw, open_page_with_tracker, switch_tab}; +use crate::card_grid::{CardGrid, row_height}; +use crate::card_images::tests::{PORTRAIT_JPEG, TestDir}; + +use crate::page::{Page, Tab}; +use arena_tracker_core::{Format, SeasonScope}; +use gpui_kit::{Entity, TestAppContext, VisualTestContext, px}; // The worker saves a portrait, then tells the page: the card shows it without a restart. #[gpui::test] @@ -213,7 +223,7 @@ async fn a_statistics_error_is_said_once_during_a_champ_select(cx: &mut TestAppC page.read_with(&window, |p, _| { assert_eq!( p.stats_notice(), - Some(super::super::home::StatsNotice::Error) + Some(crate::page::home::StatsNotice::Error) ); assert_eq!(p.error().map(String::as_str), Some(error)); }); diff --git a/crates/app/src/page/tests/sorting.rs b/crates/app/src/page/tests/sorting.rs index b0cc7eb..e763d90 100644 --- a/crates/app/src/page/tests/sorting.rs +++ b/crates/app/src/page/tests/sorting.rs @@ -1,4 +1,19 @@ -use super::*; +use super::champ_select_fixtures::{ + ALL_A_TO_Z, ANVIL_A_TO_Z, ANVIL_BY_MASTERY, OTHERS_A_TO_Z, OTHERS_BY_MASTERY, anvil_cards, + click_others, frames, ids, joueur_tracker_with, leave, others_cards, reasons, send, +}; +use super::page_fixtures::{ + center, draw, grid_names, open_page_in_season, open_page_with_sort, open_page_with_tracker, + season, show, statistics, +}; +use super::sorting_fixtures::{ + A_TO_Z, BY_MASTERY, pick_sort, record_sorts, reorders, rows_with_points, +}; +use crate::card::Reason; + +use arena_tracker_core::{ChampionRow, ChampionSort, RiotApi, StateFilter, Tracker}; +use gpui_kit::{Modifiers, TestAppContext, VisualTestContext}; +use std::path::Path; #[gpui::test] fn the_home_follows_the_mastery_points_until_another_sort_is_chosen(cx: &mut TestAppContext) { diff --git a/crates/app/src/page/tests/sorting_fixtures.rs b/crates/app/src/page/tests/sorting_fixtures.rs new file mode 100644 index 0000000..dcba97f --- /dev/null +++ b/crates/app/src/page/tests/sorting_fixtures.rs @@ -0,0 +1,72 @@ +use super::page_fixtures::draw; +use crate::champion_table::tests::row; +use crate::page::{ChampionSortChosen, Page}; +use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, ChampionSort, ChampionState}; +use gpui_kit::component::select::SelectEvent; +use gpui_kit::{Entity, VisualTestContext}; +use std::cell::RefCell; +use std::rc::Rc; + +// The sort of the cards (#76). + +/// A row with a name, an id and its Mastery Points. +pub(super) fn with_points(id: u32, name: &str, points: Option) -> ChampionRow { + ChampionRow { + champion: Champion { + id, + key: name.into(), + name: name.into(), + }, + state: Some(ChampionState::NeverPlayed), + challenge: Some(ChampionChallenge::default()), + mastery_points: points, + ..row(name) + } +} + +/// A to Z, as the statistics give them. +pub(super) fn rows_with_points() -> Vec { + vec![ + with_points(1, "Ahri", None), + with_points(2, "Brand", Some(500)), + with_points(3, "Garen", Some(9_000)), + with_points(4, "Jinx", Some(500)), + with_points(5, "Lux", Some(0)), + with_points(6, "Zed", None), + ] +} + +pub(super) const BY_MASTERY: [&str; 6] = ["Garen", "Brand", "Jinx", "Lux", "Ahri", "Zed"]; + +pub(super) const A_TO_Z: [&str; 6] = ["Ahri", "Brand", "Garen", "Jinx", "Lux", "Zed"]; + +/// The sorts the page reports, in order. +pub(super) fn record_sorts( + page: &Entity, + cx: &mut VisualTestContext, +) -> Rc>> { + let chosen = Rc::new(RefCell::new(Vec::new())); + let events = chosen.clone(); + cx.update(|_, cx| { + cx.subscribe(page, move |_, event: &ChampionSortChosen, _| { + events.borrow_mut().push(event.0) + }) + .detach() + }); + chosen +} + +/// The player picks `label` in the sort selector. +pub(super) fn pick_sort(page: &Entity, cx: &mut VisualTestContext, label: &'static str) { + let select = page.read_with(cx, |p, _| p.sort_select.clone()); + cx.update(|_, cx| { + select.update(cx, |_, cx| { + cx.emit(SelectEvent::Confirm(Some(label.into()))) + }) + }); + draw(cx); +} + +pub(super) fn reorders(page: &Entity, cx: &mut VisualTestContext) -> usize { + page.read_with(cx, |p, _| p.reorders) +} diff --git a/crates/app/src/page/updates.rs b/crates/app/src/page/worker_messages.rs similarity index 56% rename from crates/app/src/page/updates.rs rename to crates/app/src/page/worker_messages.rs index 5d3db47..635a752 100644 --- a/crates/app/src/page/updates.rs +++ b/crates/app/src/page/worker_messages.rs @@ -1,5 +1,5 @@ -use super::{ChampSelectTransition, Page, RELOAD_EVERY, Tab}; -use crate::worker::{LiveChampSelect, Msg, spawn_refresh}; +use super::{Page, RELOAD_EVERY}; +use crate::worker::{Msg, spawn_refresh}; use gpui_kit::*; impl Page { @@ -103,74 +103,6 @@ impl Page { cx.notify(); } - /// The champ select the client reports changed: entered, left, another one, or the same - /// one with new picks and bans. - pub(super) fn change_champ_select( - &mut self, - champ_select: LiveChampSelect, - window: &mut Window, - cx: &mut Context, - ) { - 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); - self.champ_select = champ_select; - if changed_page { - if self.in_champ_select() { - // The champ select is about the Challenge, whatever tab was open. - self.tab = Tab::Challenge; - // Nothing plays during a champ select: what waited is no longer news. - self.stop_holding(); - self.end_match(cx); - self.end_fade(window, cx); - // The home grid gives way to the champ select's sections. - self.home_grid - .update(cx, |grid, cx| grid.release_images(window, cx)); - // Its entry plays once the window shows it (#63 reveals it without focus). - self.entry_waiting = true; - } else { - 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(); - } - } - if switch { - // The Account belongs to the signed-in Riot ID: resolve it once, not on every - // statistics preparation. - self.champ_select_riot_id = None; - self.stats_generation += 1; - self.stats = None; - self.stats_error = None; - self.forget_home(); - self.stored = None; - self.reorder(); - // A new champ select starts with « Autres champions » folded and searchless. - self.fold_others(window, cx); - self.reload_in_background(window, cx); - // Nor does the banner keep the previous scope's Challenge while the new one - // loads: its Season, its ticks and its splash go with the statistics. - self.prepare_banner(cx); - } - if 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); - } - fn mark_crashed(&mut self) { self.pending_round = false; self.progress = None; diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index d96e909..5d5d540 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -86,7 +86,7 @@ impl KeyForm { window: &mut Window, cx: &mut Context, ) -> Self { - let preferences = store.config.preferences; + let preferences = store.preferences(); apply_theme(preferences.theme, window, cx); let (notice_shown, notices) = unbounded(); let notice_listener = cx.spawn(async move |this, cx| { @@ -110,10 +110,10 @@ impl KeyForm { } } }); - let notice = (!store.config.tray_notice_shown).then(|| notice_shown.clone()); + let notice = (!store.tray_notice_shown()).then(|| notice_shown.clone()); let tray = Tray::install_saved(window, preferences.close_to_tray, notice, cx); let appearance = cx.observe_window_appearance(window, |this, window, cx| { - apply_theme(this.store.config.preferences.theme, window, cx); + apply_theme(this.store.preferences().theme, window, cx); }); let placeholder = if store.has_key() { PLACEHOLDER_SAVED @@ -165,7 +165,7 @@ impl KeyForm { /// Checks the chosen channel in the background, after the running check if there is one. fn check_updates(&mut self) { if release::VERSION.is_some() && self.update_checks.request() { - let channel = channel(self.store.config.preferences); + let channel = channel(self.store.preferences()); spawn_update_check(channel, self.updates.clone()); } } @@ -173,10 +173,10 @@ impl KeyForm { /// Only a check of the channel chosen now can make an update ready. pub(crate) fn update_checked(&mut self, checked: UpdateChecked, cx: &mut Context) { if self.update_checks.finished() { - let channel = channel(self.store.config.preferences); + let channel = channel(self.store.preferences()); spawn_update_check(channel, self.updates.clone()); } - if checked.channel == channel(self.store.config.preferences) { + if checked.channel == channel(self.store.preferences()) { let ready = (checked.ready) .map(|version| format!("Mise à jour prête : version {version}").into()); self.set_ready(ready, cx); @@ -196,7 +196,7 @@ impl KeyForm { /// « Mise à jour prête », or why an installed beta stays on the stable channel. fn update_status(&self) -> Option { let beta = release::VERSION.is_some_and(|version| version.contains("-beta.")); - let stable = channel(self.store.config.preferences) == UpdateChannel::Stable; + let stable = channel(self.store.preferences()) == UpdateChannel::Stable; (self.ready.clone()).or_else(|| (beta && stable).then_some(STABLE_AFTER_BETA.into())) } @@ -214,12 +214,12 @@ impl KeyForm { window: &mut Window, cx: &mut Context, ) { - let previous = self.store.config.preferences; + let previous = self.store.preferences(); if previous == preferences { return; } if preferences.close_to_tray && !previous.close_to_tray { - let notice = (!self.store.config.tray_notice_shown).then(|| self.notice_shown.clone()); + let notice = (!self.store.tray_notice_shown()).then(|| self.notice_shown.clone()); self.tray = Tray::install(window, notice, cx); if self.tray.is_none() { self.preference_error = Some(UNAVAILABLE.into()); @@ -238,7 +238,7 @@ impl KeyForm { } None }; - if !self.store.config.preferences.close_to_tray + if !self.store.preferences().close_to_tray && let Some(tray) = self.tray.take() { tray.uninstall(); @@ -264,9 +264,9 @@ impl KeyForm { pub fn save_champion_sort(&mut self, sort: ChampionSort, cx: &mut Context) { let preferences = Preferences { champion_sort: Some(sort), - ..self.store.config.preferences + ..self.store.preferences() }; - if preferences == self.store.config.preferences { + if preferences == self.store.preferences() { return; } self.preference_error = self @@ -278,7 +278,7 @@ impl KeyForm { } fn preferences(&self, cx: &mut Context) -> impl IntoElement { - let preferences = self.store.config.preferences; + let preferences = self.store.preferences(); let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger); let logon_available = self.logon_launch.available(); div() @@ -310,7 +310,7 @@ impl KeyForm { this.set_preferences( Preferences { close_to_tray: *enabled, - ..this.store.config.preferences + ..this.store.preferences() }, window, cx, @@ -330,7 +330,7 @@ impl KeyForm { this.set_preferences( Preferences { theme: THEMES[*index].0, - ..this.store.config.preferences + ..this.store.preferences() }, window, cx, @@ -355,7 +355,7 @@ impl KeyForm { this.set_preferences( Preferences { update_channel: Some(CHANNELS[*index].0), - ..this.store.config.preferences + ..this.store.preferences() }, window, cx, @@ -386,7 +386,7 @@ impl KeyForm { if !self.can_restart() { return; } - match release::restart_to_update(channel(self.store.config.preferences)) { + match release::restart_to_update(channel(self.store.preferences())) { Ok(()) => { self.set_ready(None, cx); cx.quit(); diff --git a/crates/app/src/settings/store.rs b/crates/app/src/settings/store.rs index 1b266d2..3d5ffef 100644 --- a/crates/app/src/settings/store.rs +++ b/crates/app/src/settings/store.rs @@ -6,7 +6,7 @@ use arena_tracker_core::{Config, Error, Preferences, RiotApi}; /// The local config file and the running Riot client that uses its key. pub struct KeyStore { path: PathBuf, - pub(super) config: Config, + config: Config, api: Arc, } @@ -23,6 +23,10 @@ impl KeyStore { self.config.preferences } + pub(super) fn tray_notice_shown(&self) -> bool { + self.config.tray_notice_shown + } + /// Writes the key to the config file and hands it to the Riot client, no restart needed. pub(super) fn save(&mut self, key: &str) -> Result<(), Error> { let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string()); diff --git a/crates/app/src/settings/tests.rs b/crates/app/src/settings/tests.rs index 8771b54..3d7bebb 100644 --- a/crates/app/src/settings/tests.rs +++ b/crates/app/src/settings/tests.rs @@ -29,7 +29,7 @@ fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut Test form.update(cx, |form, cx| { let preferences = Preferences { update_channel: Some(channel), - ..form.store.config.preferences + ..form.store.preferences() }; form.set_preferences(preferences, window, cx); }) diff --git a/crates/app/src/stage.rs b/crates/app/src/stage.rs index 099b322..3e7ecb8 100644 --- a/crates/app/src/stage.rs +++ b/crates/app/src/stage.rs @@ -5,382 +5,10 @@ //! last placed them, as a lifted card does (`card_lift`): the grid itself is never drawn again. mod hand; +mod motion; pub(crate) use hand::{HandMotion, hand_layer}; - -use std::rc::Rc; -use std::time::{Duration, Instant}; - -use gpui_kit::base::Easing; -use gpui_kit::component::ActiveTheme as _; -use gpui_kit::*; - -use crate::card::{Card, Pose}; -use crate::card_grid::TAKEN_DROP; -use crate::card_lift::{Lifted, Lowered}; -use crate::motion::{ease_in, ease_out}; -use crate::theme::gold_soft; - -/// How long the band of light takes to cross the window, fading as it goes. -const SWEEP: Duration = Duration::from_millis(900); -/// How long the title takes to come in, rising. -const TITLE: Duration = Duration::from_millis(700); -/// How far below its place the title starts. -const TITLE_RISE: f32 = 8.; -/// When the first card of the hand leaves the bottom of the window. -const FIRST_DEAL: Duration = Duration::from_millis(380); -/// How long after the card before it each next card leaves. -const DEAL_EVERY: Duration = Duration::from_millis(110); -/// How long a card takes from the bottom of the window to its place. -const DEAL: Duration = Duration::from_millis(700); -/// How long a card of the hand takes to leave, the last one first. -const LEAVE: Duration = Duration::from_millis(320); -/// How long after the card after it each card leaves. -const LEAVE_EVERY: Duration = Duration::from_millis(35); -/// How far down a card of the hand goes as it leaves. -const LEAVE_DROP: f32 = 48.; -/// How long the hand leaves alone before the veil of the tabs starts covering the screen. -pub(crate) const BEFORE_VEIL: Duration = Duration::from_millis(240); -/// How long a card an ally just took takes to go down to its place (`card_grid::TAKEN_DROP`). -const TAKEN: Duration = Duration::from_millis(350); -/// How long it takes to grey, its new badge coming in. -const TAKEN_FADE: Duration = Duration::from_millis(500); -/// The band of light's curve, as CSS's `ease-out`. -const SWEEP_CURVE: Easing = Easing::EaseOut; -/// A card dealt's curve, the reference's `cubic-bezier(.2, 1.25, .35, 1)`: it goes a little past -/// its place before settling there. -const DEAL_CURVE: Easing = Easing::CubicBezier { - x1: 0.2, - y1: 1.25, - x2: 0.35, - y2: 1., -}; - -/// How far an animation of `duration` started at `start` is, 0 to 1; 0 before it starts. -fn progress(start: Instant, duration: Duration, now: Instant) -> f32 { - let elapsed = now.saturating_duration_since(start); - (elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.) -} - -/// The entry into a champ select, from the moment the window shows it. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct Entry { - start: Instant, - /// When the deal's clock started: the entry's own start, or later when the hand's cards come - /// after the first one should have left (the statistics load at each new champ select). - deal: Option, -} - -/// Where a card of the hand is in the deal. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Dealt { - /// Not dealt yet: its place is empty. - Waiting, - /// On its way, 0 to 1. - Moving(f32), - /// In its place: the grid's own card. - Landed, -} - -impl Dealt { - /// How much of the way it still has to go (as `deal_pose`), and its opacity: a card not - /// dealt yet is out of sight. - pub fn pose(self) -> (f32, f32) { - match self { - Dealt::Waiting => (0., 0.), - Dealt::Moving(progress) => deal_pose(progress), - Dealt::Landed => (0., 1.), - } - } -} - -impl Entry { - /// An entry starting `now`, its hand waiting for its cards. - pub fn new(now: Instant) -> Entry { - Entry { - start: now, - deal: None, - } - } - - /// The hand has its cards: they are dealt on the entry's clock, or from now on when they - /// come late. Their reasons changing later deals nothing again. - pub fn cards_arrived(&mut self, now: Instant) { - if self.deal.is_none() { - let late = now.checked_sub(FIRST_DEAL).unwrap_or(self.start); - self.deal = Some(late.max(self.start)); - } - } - - /// How far the band of light has crossed, 0 to 1, while it does; as CSS's `ease-out`. - pub fn sweep(&self, now: Instant) -> Option { - let progress = progress(self.start, SWEEP, now); - (progress < 1.).then(|| SWEEP_CURVE.sample(progress)) - } - - /// How far the title has come in, 0 to 1. - pub fn title(&self, now: Instant) -> f32 { - ease_out(progress(self.start, TITLE, now)) - } - - /// Where card `ix` of the hand (in the hand's order) is in the deal. - pub fn dealt(&self, ix: usize, now: Instant) -> Dealt { - let Some(deal) = self.deal else { - // No card yet: none to hide. - return Dealt::Landed; - }; - let leaves = deal + FIRST_DEAL + DEAL_EVERY * ix as u32; - if now < leaves { - return Dealt::Waiting; - } - match progress(leaves, DEAL, now) { - 1. => Dealt::Landed, - progress => Dealt::Moving(progress), - } - } - - /// Whether the hand has its cards, dealt or being dealt. - pub fn dealing(&self) -> bool { - self.deal.is_some() - } - - /// Whether card `ix` of the hand is in its place. - pub fn landed(&self, ix: usize, now: Instant) -> bool { - self.dealt(ix, now) == Dealt::Landed - } - - /// Whether anything of the entry still moves, the hand holding `cards`. Waiting for the - /// hand's cards moves nothing. The time gone is enough: no curve is solved. - pub fn animating(&self, cards: usize, now: Instant) -> bool { - now < self.start + SWEEP.max(TITLE) || (cards > 0 && !self.landed(cards - 1, now)) - } - - /// Whether the entry is over: the hand had its cards, and they are all in their place. - pub fn over(&self, cards: usize, now: Instant) -> bool { - self.deal.is_some() && !self.animating(cards, now) - } - - /// The title's opacity and how far below its place it is. - pub fn title_pose(&self, now: Instant) -> (f32, f32) { - let progress = self.title(now); - (progress, TITLE_RISE * (1. - progress)) - } -} - -/// A card on its way from the bottom of the window: how much of the way is left (below 0 past -/// its place, as the reference's curve goes beyond it before settling), and its opacity. -fn deal_pose(progress: f32) -> (f32, f32) { - let done = DEAL_CURVE.sample(progress); - (1. - done, done.clamp(0., 1.)) -} - -/// The exit from a champ select: the hand's cards go down and fade, the last one first, each -/// from where it was when the champ select ended. -#[derive(Clone, Debug)] -pub(crate) struct Leave { - start: Instant, - /// Where each card of the hand was, in the hand's order: read once, when the champ select - /// ended. - cards: Rc<[CardAtEnd]>, -} - -/// Where a card of the hand was when the champ select ended, as it was drawn then. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct CardAtEnd { - pub id: u32, - /// How much of the deal's way it still had to go (as `deal_pose`), 0 once in its place. - pub left: f32, - /// Its opacity: 0 for a card not dealt yet, which stays out of sight. - pub opacity: f32, - /// How far it was lifted (`card_lift`), and the hand's veil on it. - pub pose: Pose, - /// How far above its place it was: its rise, and an ally's confirmation not over. - pub above: f32, - /// The card as it was before an ally's confirmation not over, fading over it. - pub before: Option, -} - -/// The card as it was before an ally's confirmation, over the card now. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct Before { - pub card: Rc, - pub above: f32, - pub opacity: f32, -} - -/// How far a card of the hand went from where it was. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct Leaving { - /// How far down. - pub down: f32, - /// How much of its opacity it keeps: 1 at first, 0 once gone. - pub opacity: f32, -} - -/// What the hand looked like when the champ select ended. -pub(crate) struct HandAt<'a> { - /// The entry it was in, if its cards were still dealt. - pub entry: Option, - /// Its cards lifted or settling back (`card_lift`). - pub lifted: &'a [Lifted], - /// The hand's veil on the others. - pub veil: f32, - /// Its cards going down after an ally's confirmation. - pub taken: &'a [Taken], -} - -impl Leave { - /// The hand of `cards` leaving from `now`, each card from where `hand` shows it. - pub fn new(cards: &[Card], hand: HandAt, now: Instant) -> Leave { - let cards = cards - .iter() - .enumerate() - .map(|(ix, card)| { - let dealt = hand.entry.map_or(Dealt::Landed, |e| e.dealt(ix, now)); - let (left, opacity) = dealt.pose(); - let progress = (hand.lifted.iter()) - .find(|lifted| lifted.id == card.id) - .map_or(0., |lifted| lifted.progress); - let pose = Pose { - mark_fill: None, - progress, - // Settling back, it goes under the veil, as `card_lift` draws it. - veil: hand.veil * (1. - progress), - // The hand leaves only when the Windows setting lets it move. - moves: true, - }; - let taken = hand.taken.iter().find(|taken| taken.id == card.id); - let lowered = taken.map_or(0., |taken| taken.above(now)); - CardAtEnd { - id: card.id, - left, - opacity, - pose, - above: pose.rise(card) + lowered, - before: taken.map(|taken| Before { - above: pose.rise(&taken.before) + lowered, - card: taken.before.clone(), - opacity: taken.before(now), - }), - } - }) - .collect(); - Leave { start: now, cards } - } - - /// Where card `id` was when the champ select ended, and its index in the hand then, if it - /// was there: `ix`, its index now, is looked at first. The hand may change as it leaves - /// (statistics reloaded). - pub fn card(&self, id: u32, ix: usize) -> Option<(usize, &CardAtEnd)> { - match self.cards.get(ix) { - Some(was) if was.id == id => Some((ix, was)), - _ => (self.cards.iter().enumerate()).find(|(_, was)| was.id == id), - } - } - - /// How far card `ix` of the hand, as it was when the champ select ended, went from where - /// it was. - pub fn pose(&self, ix: usize, now: Instant) -> Leaving { - let after = self.cards.len().saturating_sub(ix + 1) as u32; - let done = ease_in(progress(self.start + LEAVE_EVERY * after, LEAVE, now)); - Leaving { - down: LEAVE_DROP * done, - opacity: 1. - done, - } - } -} - -/// A card of the hand an ally just took: it goes down to its place, lower than the others, and -/// greys as its badge comes in, the card as it was fading over it. -#[derive(Clone, Debug)] -pub(crate) struct Taken { - pub id: u32, - /// Shared by every frame that draws it. - before: Rc, - start: Instant, -} - -impl Taken { - /// Card `id` taken `now`, `before` being how it looked until then. - pub fn new(id: u32, before: Rc, now: Instant) -> Taken { - Taken { - id, - before, - start: now, - } - } - - /// How far above its place the card is. - pub fn above(&self, now: Instant) -> f32 { - TAKEN_DROP * (1. - ease_out(progress(self.start, TAKEN, now))) - } - - /// The opacity of the card as it was, over the one it is now. - pub fn before(&self, now: Instant) -> f32 { - 1. - progress(self.start, TAKEN_FADE, now) - } - - /// Whether it is in its place and greyed. - pub fn done(&self, now: Instant) -> bool { - progress(self.start, TAKEN_FADE, now) >= 1. - } - - /// The card as a lifted one draws it: it goes down to its place as it greys. - pub fn lowered(&self, now: Instant) -> Lowered { - Lowered { - id: self.id, - above: self.above(now), - before: self.before.clone(), - opacity: self.before(now), - } - } -} - -/// The band of gold light crossing the window, `progress` 0 to 1, `window` its size: it goes -/// from left to right and fades as it goes, as the reference's gradient (GPUI's gradients have -/// two stops: the band is four of them side by side). Over the whole window, the title bar -/// included, and painted after everything else, the hand's moving cards too. It catches no -/// pointer. -pub(crate) fn sweep(progress: f32, window: Size, cx: &App) -> AnyElement { - let width = window.width.as_f32(); - let gold = gold_soft(cx.theme()); - let clear = gold.opacity(0.); - let light = hsla(0., 0., 1., 0.16); - // The reference's band, 28 % of a gradient three windows wide: 0.375 of a window to gold, - // then 0.045 to the white of its middle, and back. - let (outer, inner) = (0.375 * width, 0.045 * width); - let middle = -0.5 * width + 2. * width * progress; - let parts = [ - (middle - inner - outer, outer, clear, gold), - (middle - inner, inner, gold, light), - (middle, inner, light, gold), - (middle + inner, outer, gold, clear), - ]; - let band = div() - .relative() - .w(window.width) - .h(window.height) - .overflow_hidden() - .opacity(1. - progress) - .debug_selector(|| "sweep".into()) - .children(parts.map(|(left, part, from, to)| { - div() - .absolute() - .top_0() - .bottom_0() - .left(px(left)) - .w(px(part)) - .bg(linear_gradient( - 90., - linear_color_stop(from, 0.), - linear_color_stop(to, 1.), - )) - })); - // Over the deferred layers of the hand and of the lifted cards (priority 0). - deferred(anchored().position(point(px(0.), px(0.))).child(band)) - .with_priority(1) - .into_any_element() -} +pub(crate) use motion::{BEFORE_VEIL, Entry, HandAt, Leave, Taken, sweep}; #[cfg(test)] mod tests; diff --git a/crates/app/src/stage/hand.rs b/crates/app/src/stage/hand.rs index f19aeb7..c350591 100644 --- a/crates/app/src/stage/hand.rs +++ b/crates/app/src/stage/hand.rs @@ -1,7 +1,8 @@ use gpui_kit::component::ActiveTheme as _; use gpui_kit::*; -use super::{Entry, Leave, Leaving, Taken}; +use super::motion::Leaving; +use super::{Entry, Leave, Taken}; use crate::card::{self, Card, Pose}; use crate::card_grid::Placements; use crate::card_images::CardImages; diff --git a/crates/app/src/stage/motion.rs b/crates/app/src/stage/motion.rs new file mode 100644 index 0000000..3b33685 --- /dev/null +++ b/crates/app/src/stage/motion.rs @@ -0,0 +1,373 @@ +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use gpui_kit::base::Easing; +use gpui_kit::component::ActiveTheme as _; +use gpui_kit::*; + +use crate::card::{Card, Pose}; +use crate::card_grid::TAKEN_DROP; +use crate::card_lift::{Lifted, Lowered}; +use crate::motion::{ease_in, ease_out}; +use crate::theme::gold_soft; + +/// How long the band of light takes to cross the window, fading as it goes. +const SWEEP: Duration = Duration::from_millis(900); +/// How long the title takes to come in, rising. +const TITLE: Duration = Duration::from_millis(700); +/// How far below its place the title starts. +const TITLE_RISE: f32 = 8.; +/// When the first card of the hand leaves the bottom of the window. +const FIRST_DEAL: Duration = Duration::from_millis(380); +/// How long after the card before it each next card leaves. +const DEAL_EVERY: Duration = Duration::from_millis(110); +/// How long a card takes from the bottom of the window to its place. +const DEAL: Duration = Duration::from_millis(700); +/// How long a card of the hand takes to leave, the last one first. +const LEAVE: Duration = Duration::from_millis(320); +/// How long after the card after it each card leaves. +const LEAVE_EVERY: Duration = Duration::from_millis(35); +/// How far down a card of the hand goes as it leaves. +const LEAVE_DROP: f32 = 48.; +/// How long the hand leaves alone before the veil of the tabs starts covering the screen. +pub(crate) const BEFORE_VEIL: Duration = Duration::from_millis(240); +/// How long a card an ally just took takes to go down to its place (`card_grid::TAKEN_DROP`). +const TAKEN: Duration = Duration::from_millis(350); +/// How long it takes to grey, its new badge coming in. +const TAKEN_FADE: Duration = Duration::from_millis(500); +/// The band of light's curve, as CSS's `ease-out`. +const SWEEP_CURVE: Easing = Easing::EaseOut; +/// A card dealt's curve, the reference's `cubic-bezier(.2, 1.25, .35, 1)`: it goes a little past +/// its place before settling there. +const DEAL_CURVE: Easing = Easing::CubicBezier { + x1: 0.2, + y1: 1.25, + x2: 0.35, + y2: 1., +}; + +/// How far an animation of `duration` started at `start` is, 0 to 1; 0 before it starts. +fn progress(start: Instant, duration: Duration, now: Instant) -> f32 { + let elapsed = now.saturating_duration_since(start); + (elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.) +} + +/// The entry into a champ select, from the moment the window shows it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Entry { + start: Instant, + /// When the deal's clock started: the entry's own start, or later when the hand's cards come + /// after the first one should have left (the statistics load at each new champ select). + deal: Option, +} + +/// Where a card of the hand is in the deal. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Dealt { + /// Not dealt yet: its place is empty. + Waiting, + /// On its way, 0 to 1. + Moving(f32), + /// In its place: the grid's own card. + Landed, +} + +impl Dealt { + /// How much of the way it still has to go (as `deal_pose`), and its opacity: a card not + /// dealt yet is out of sight. + pub fn pose(self) -> (f32, f32) { + match self { + Dealt::Waiting => (0., 0.), + Dealt::Moving(progress) => deal_pose(progress), + Dealt::Landed => (0., 1.), + } + } +} + +impl Entry { + /// An entry starting `now`, its hand waiting for its cards. + pub fn new(now: Instant) -> Entry { + Entry { + start: now, + deal: None, + } + } + + /// The hand has its cards: they are dealt on the entry's clock, or from now on when they + /// come late. Their reasons changing later deals nothing again. + pub fn cards_arrived(&mut self, now: Instant) { + if self.deal.is_none() { + let late = now.checked_sub(FIRST_DEAL).unwrap_or(self.start); + self.deal = Some(late.max(self.start)); + } + } + + /// How far the band of light has crossed, 0 to 1, while it does; as CSS's `ease-out`. + pub fn sweep(&self, now: Instant) -> Option { + let progress = progress(self.start, SWEEP, now); + (progress < 1.).then(|| SWEEP_CURVE.sample(progress)) + } + + /// How far the title has come in, 0 to 1. + pub fn title(&self, now: Instant) -> f32 { + ease_out(progress(self.start, TITLE, now)) + } + + /// Where card `ix` of the hand (in the hand's order) is in the deal. + pub fn dealt(&self, ix: usize, now: Instant) -> Dealt { + let Some(deal) = self.deal else { + // No card yet: none to hide. + return Dealt::Landed; + }; + let leaves = deal + FIRST_DEAL + DEAL_EVERY * ix as u32; + if now < leaves { + return Dealt::Waiting; + } + match progress(leaves, DEAL, now) { + 1. => Dealt::Landed, + progress => Dealt::Moving(progress), + } + } + + /// Whether the hand has its cards, dealt or being dealt. + pub fn dealing(&self) -> bool { + self.deal.is_some() + } + + /// Whether card `ix` of the hand is in its place. + pub fn landed(&self, ix: usize, now: Instant) -> bool { + self.dealt(ix, now) == Dealt::Landed + } + + /// Whether anything of the entry still moves, the hand holding `cards`. Waiting for the + /// hand's cards moves nothing. The time gone is enough: no curve is solved. + pub fn animating(&self, cards: usize, now: Instant) -> bool { + now < self.start + SWEEP.max(TITLE) || (cards > 0 && !self.landed(cards - 1, now)) + } + + /// Whether the entry is over: the hand had its cards, and they are all in their place. + pub fn over(&self, cards: usize, now: Instant) -> bool { + self.deal.is_some() && !self.animating(cards, now) + } + + /// The title's opacity and how far below its place it is. + pub fn title_pose(&self, now: Instant) -> (f32, f32) { + let progress = self.title(now); + (progress, TITLE_RISE * (1. - progress)) + } +} + +/// A card on its way from the bottom of the window: how much of the way is left (below 0 past +/// its place, as the reference's curve goes beyond it before settling), and its opacity. +fn deal_pose(progress: f32) -> (f32, f32) { + let done = DEAL_CURVE.sample(progress); + (1. - done, done.clamp(0., 1.)) +} + +/// The exit from a champ select: the hand's cards go down and fade, the last one first, each +/// from where it was when the champ select ended. +#[derive(Clone, Debug)] +pub(crate) struct Leave { + start: Instant, + /// Where each card of the hand was, in the hand's order: read once, when the champ select + /// ended. + cards: Rc<[CardAtEnd]>, +} + +/// Where a card of the hand was when the champ select ended, as it was drawn then. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct CardAtEnd { + pub id: u32, + /// How much of the deal's way it still had to go (as `deal_pose`), 0 once in its place. + pub left: f32, + /// Its opacity: 0 for a card not dealt yet, which stays out of sight. + pub opacity: f32, + /// How far it was lifted (`card_lift`), and the hand's veil on it. + pub pose: Pose, + /// How far above its place it was: its rise, and an ally's confirmation not over. + pub above: f32, + /// The card as it was before an ally's confirmation not over, fading over it. + pub before: Option, +} + +/// The card as it was before an ally's confirmation, over the card now. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Before { + pub card: Rc, + pub above: f32, + pub opacity: f32, +} + +/// How far a card of the hand went from where it was. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Leaving { + /// How far down. + pub down: f32, + /// How much of its opacity it keeps: 1 at first, 0 once gone. + pub opacity: f32, +} + +/// What the hand looked like when the champ select ended. +pub(crate) struct HandAt<'a> { + /// The entry it was in, if its cards were still dealt. + pub entry: Option, + /// Its cards lifted or settling back (`card_lift`). + pub lifted: &'a [Lifted], + /// The hand's veil on the others. + pub veil: f32, + /// Its cards going down after an ally's confirmation. + pub taken: &'a [Taken], +} + +impl Leave { + /// The hand of `cards` leaving from `now`, each card from where `hand` shows it. + pub fn new(cards: &[Card], hand: HandAt, now: Instant) -> Leave { + let cards = cards + .iter() + .enumerate() + .map(|(ix, card)| { + let dealt = hand.entry.map_or(Dealt::Landed, |e| e.dealt(ix, now)); + let (left, opacity) = dealt.pose(); + let progress = (hand.lifted.iter()) + .find(|lifted| lifted.id == card.id) + .map_or(0., |lifted| lifted.progress); + let pose = Pose { + mark_fill: None, + progress, + // Settling back, it goes under the veil, as `card_lift` draws it. + veil: hand.veil * (1. - progress), + // The hand leaves only when the Windows setting lets it move. + moves: true, + }; + let taken = hand.taken.iter().find(|taken| taken.id == card.id); + let lowered = taken.map_or(0., |taken| taken.above(now)); + CardAtEnd { + id: card.id, + left, + opacity, + pose, + above: pose.rise(card) + lowered, + before: taken.map(|taken| Before { + above: pose.rise(&taken.before) + lowered, + card: taken.before.clone(), + opacity: taken.before(now), + }), + } + }) + .collect(); + Leave { start: now, cards } + } + + /// Where card `id` was when the champ select ended, and its index in the hand then, if it + /// was there: `ix`, its index now, is looked at first. The hand may change as it leaves + /// (statistics reloaded). + pub fn card(&self, id: u32, ix: usize) -> Option<(usize, &CardAtEnd)> { + match self.cards.get(ix) { + Some(was) if was.id == id => Some((ix, was)), + _ => (self.cards.iter().enumerate()).find(|(_, was)| was.id == id), + } + } + + /// How far card `ix` of the hand, as it was when the champ select ended, went from where + /// it was. + pub fn pose(&self, ix: usize, now: Instant) -> Leaving { + let after = self.cards.len().saturating_sub(ix + 1) as u32; + let done = ease_in(progress(self.start + LEAVE_EVERY * after, LEAVE, now)); + Leaving { + down: LEAVE_DROP * done, + opacity: 1. - done, + } + } +} + +/// A card of the hand an ally just took: it goes down to its place, lower than the others, and +/// greys as its badge comes in, the card as it was fading over it. +#[derive(Clone, Debug)] +pub(crate) struct Taken { + pub id: u32, + /// Shared by every frame that draws it. + pub(super) before: Rc, + start: Instant, +} + +impl Taken { + /// Card `id` taken `now`, `before` being how it looked until then. + pub fn new(id: u32, before: Rc, now: Instant) -> Taken { + Taken { + id, + before, + start: now, + } + } + + /// How far above its place the card is. + pub fn above(&self, now: Instant) -> f32 { + TAKEN_DROP * (1. - ease_out(progress(self.start, TAKEN, now))) + } + + /// The opacity of the card as it was, over the one it is now. + pub fn before(&self, now: Instant) -> f32 { + 1. - progress(self.start, TAKEN_FADE, now) + } + + /// Whether it is in its place and greyed. + pub fn done(&self, now: Instant) -> bool { + progress(self.start, TAKEN_FADE, now) >= 1. + } + + /// The card as a lifted one draws it: it goes down to its place as it greys. + pub fn lowered(&self, now: Instant) -> Lowered { + Lowered { + id: self.id, + above: self.above(now), + before: self.before.clone(), + opacity: self.before(now), + } + } +} + +/// The band of gold light crossing the window, `progress` 0 to 1, `window` its size: it goes +/// from left to right and fades as it goes, as the reference's gradient (GPUI's gradients have +/// two stops: the band is four of them side by side). Over the whole window, the title bar +/// included, and painted after everything else, the hand's moving cards too. It catches no +/// pointer. +pub(crate) fn sweep(progress: f32, window: Size, cx: &App) -> AnyElement { + let width = window.width.as_f32(); + let gold = gold_soft(cx.theme()); + let clear = gold.opacity(0.); + let light = hsla(0., 0., 1., 0.16); + // The reference's band, 28 % of a gradient three windows wide: 0.375 of a window to gold, + // then 0.045 to the white of its middle, and back. + let (outer, inner) = (0.375 * width, 0.045 * width); + let middle = -0.5 * width + 2. * width * progress; + let parts = [ + (middle - inner - outer, outer, clear, gold), + (middle - inner, inner, gold, light), + (middle, inner, light, gold), + (middle + inner, outer, gold, clear), + ]; + let band = div() + .relative() + .w(window.width) + .h(window.height) + .overflow_hidden() + .opacity(1. - progress) + .debug_selector(|| "sweep".into()) + .children(parts.map(|(left, part, from, to)| { + div() + .absolute() + .top_0() + .bottom_0() + .left(px(left)) + .w(px(part)) + .bg(linear_gradient( + 90., + linear_color_stop(from, 0.), + linear_color_stop(to, 1.), + )) + })); + // Over the deferred layers of the hand and of the lifted cards (priority 0). + deferred(anchored().position(point(px(0.), px(0.))).child(band)) + .with_priority(1) + .into_any_element() +} diff --git a/crates/app/src/stage/tests.rs b/crates/app/src/stage/tests.rs index 6769b78..cb95899 100644 --- a/crates/app/src/stage/tests.rs +++ b/crates/app/src/stage/tests.rs @@ -2,7 +2,8 @@ use std::time::{Duration, Instant}; use std::rc::Rc; -use super::{Dealt, Entry, HandAt, Leave, Leaving, Taken, deal_pose}; +use super::motion::{Dealt, Leaving}; +use super::{Entry, HandAt, Leave, Taken}; use crate::card::Card; use crate::card_lift::Lifted; @@ -66,15 +67,15 @@ fn cards_coming_late_are_dealt_from_then_and_only_once() { #[test] fn a_card_dealt_comes_from_below_goes_a_little_past_its_place_and_settles() { - assert_eq!(deal_pose(0.), (1., 0.)); + assert_eq!(Dealt::Moving(0.).pose(), (1., 0.)); // Fast at first: most of the way in a quarter of the time. - let (left, opacity) = deal_pose(0.25); + let (left, opacity) = Dealt::Moving(0.25).pose(); assert!(left > 0. && left < 0.5 && opacity > 0.5, "{left} {opacity}"); let past = (30..100) - .map(|i| deal_pose(i as f32 / 100.).0) + .map(|i| Dealt::Moving(i as f32 / 100.).pose().0) .fold(1f32, f32::min); assert!(past < 0., "{past}"); - let (left, opacity) = deal_pose(1.); + let (left, opacity) = Dealt::Moving(1.).pose(); assert!(left.abs() < 1e-4 && opacity == 1.); } @@ -153,7 +154,7 @@ fn a_hand_ended_during_its_deal_leaves_from_where_each_card_was() { let Dealt::Moving(progress) = entry.dealt(ix, end) else { panic!("card {ix} is not on its way"); }; - let (left, opacity) = deal_pose(progress); + let (left, opacity) = Dealt::Moving(progress).pose(); assert!(opacity > 0., "card {ix} is not seen"); // Where it was, read once. let was = leave.card(ix as u32 + 1, ix).unwrap().1; diff --git a/docs/performance.md b/docs/performance.md index 7051682..59ec102 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -49,7 +49,7 @@ The identity (ring, banner, animations; `docs/interface.md`) follows the same ru - **The foundation** (`crates/app/src/motion.rs`, with the page saying when « Défi » is visible, #86) decides whether the app animates, and when. The Windows setting reaches GPUI's `App::reduce_motion`: gpui-base reads it at start, and the window's own `WM_SETTINGCHANGE` for `SPI_SETCLIENTAREAANIMATION` reads it again, with no polling. When it is off, a tab switch shows its end state at once, and an animation asked for is not played; turning it off ends a transition running and drops the animation waiting, as soon as Windows says so (`AnimationSetting`). An animation asked for while « Défi » is not visible (window minimised or hidden in the notification area, « Statistiques », « Paramètres » or a champ select in front) waits in `Deferred`: only the strongest is kept, it plays once when « Défi » shows again, and a champ select that starts abandons it. - **Tab transitions lay a veil, never move the screen.** A cached view's cache key holds its bounds and its opacity, so fading or sliding the screen itself would draw the grid, the ring and the charts again at every frame and build the cards again. The veil, of the page's background, covers the screen leaving (130 ms) then lifts off the one arriving (280 ms). Each frame is asked for by the transition itself (`on_next_frame`), and none once the veil is lifted. A window hidden during a transition ends it at once. The champion table is a cached view too, laid out by the space the page gives it, so the veil's frames do not draw it. The screen arriving is prepared (its rows copied and sorted, its cards built) only when it is shown, so a switch undone under the veil prepares nothing. Structural tests check that a transition draws neither the grid, the ring nor the table again, builds no card, recomputes no statistics, and asks for no frame at rest. The charts arriving play gpui-kit's own short entry, as after any switch. - **A card hovered is drawn over its grid, which stays cached** (#88). The cards of a grid never change on hover or focus: the page draws the card under the pointer or the keyboard (and those settling back) lifted over the grid, in a deferred layer painted after the page, from where the grid last placed it (`card_lift.rs`). The grid records its visible cards' bounds and indices while it lays out its rows, so drawing them over it reads no layout, searches no card and copies none: the lifted card is the grid's card as it is at each frame. The layer covers each lifted card's place with the page's background, and in the hand lays the veil on the other cards. Each frame is asked for by the page's render while a card moves (`request_animation_frame`), and none once they are still. A wheel drops the grid's lifted cards at once, even at either end of the list, and so does a grid no longer shown (the home under a champ select, the hand after it) or a card filtered out, so no frame is asked for a card no longer drawn; a tab switch or « Paramètres » drops them all, and a hidden window or the setting turned off shows their end state at once. Structural tests check that hovering a card, through its whole animation, draws none of the grid, builds no card and computes no statistics, and that no frame is asked for at rest. A zoomed illustration overflows the card and is cut square by GPUI's rectangular clip: a frame of the page's background rounds its corners again, which nicks the gold glow by a few pixels at each corner. -- **A champ select enters and leaves over its cached hand** (#87). The entry starts once the window shows it, not behind « Paramètres »: a band of gold light (four two-stop gradients side by side, GPUI's gradients have two stops) crosses the page in 900 ms, the title comes in rising in 700 ms, and the Anvil champions are dealt from the bottom of the window, the first at 380 ms then one every 110 ms, each in 700 ms. The cards dealt, the card an ally just took (it rests 8 px lower in the hand, and goes down there as it greys) and the cards leaving at the end are drawn by the page over the hand's grid, in a deferred layer that covers their places with the page's background, from where the grid last placed them (`stage.rs`), as the lifted cards are: the grid is never drawn again for them, and a card's reasons changing during the deal show on it without dealing again. The hand's cards come with the statistics, loaded at each new champ select: they are dealt from when they come. A card still dealt is lifted once in its place: until a frame finds it there, the card waited for asks for frames itself. A card out of sight (the hand scrolled out of a low window, a card still under the window's bottom edge) is not built. At the end, the hand leaves (320 ms per card, from the last, 35 ms apart), each card from where it was, read once when the champ select ends (its place in the deal, its lift, the hand's veil, an ally's confirmation not over), then the veil of the tabs covers the champ select from 240 ms and the end is applied under it: the home is prepared only then. Each frame is asked for by the motion itself, none once it is over or while the hand waits for its cards; a hidden window, the page covered or the setting turned off shows the end state at once. Structural tests on the Arena capture pilot the sequence step by step and check that it draws the hand's grid again for no frame, builds no card, sorts nothing and computes no statistics, and asks for no frame at rest. +- **A champ select enters and leaves over its cached hand** (#87). The entry starts once the window shows it, not behind « Paramètres »: a band of gold light (four two-stop gradients side by side, GPUI's gradients have two stops) crosses the page in 900 ms, the title comes in rising in 700 ms, and the Anvil champions are dealt from the bottom of the window, the first at 380 ms then one every 110 ms, each in 700 ms. The cards dealt, the card an ally just took (it rests 8 px lower in the hand, and goes down there as it greys) and the cards leaving at the end are drawn by the page over the hand's grid, in a deferred layer that covers their places with the page's background, from where the grid last placed them (`crates/app/src/stage/hand.rs`), as the lifted cards are: the grid is never drawn again for them, and a card's reasons changing during the deal show on it without dealing again. The hand's cards come with the statistics, loaded at each new champ select: they are dealt from when they come. A card still dealt is lifted once in its place: until a frame finds it there, the card waited for asks for frames itself. A card out of sight (the hand scrolled out of a low window, a card still under the window's bottom edge) is not built. At the end, the hand leaves (320 ms per card, from the last, 35 ms apart), each card from where it was, read once when the champ select ends (its place in the deal, its lift, the hand's veil, an ally's confirmation not over), then the veil of the tabs covers the champ select from 240 ms and the end is applied under it: the home is prepared only then. Each frame is asked for by the motion itself, none once it is over or while the hand waits for its cards; a hidden window, the page covered or the setting turned off shows the end state at once. Structural tests on the Arena capture pilot the sequence step by step and check that it draws the hand's grid again for no frame, builds no card, sorts nothing and computes no statistics, and asks for no frame at rest. - **The end of a followed Match is drawn over the cached ring, the cached grid and the banner** (#89). The comet, the flaring tick and the bouncing crown are a function of the page's render in a layer over the ring (`Ring::match_layer`): the ring is not drawn again, and the comet and the tick are built at each frame only while the animation runs, unlike the ring's own shapes, built once per set of ticks; the crown is the ring's own, moved. The card that changes is drawn over its grid like a lifted card at rest (`card_lift.rs`), and stays in the grid until the animation ends even if the filter leaves it out. With the pointer on the grid, nothing moves under it: the grid of the new statistics (order, cards, filter) is prepared when they arrive, and the pointer leaving only puts it in place. The banner's counter rolls in painted over its place in the title, and the splash of the champion validé settles in with the banner's own decode. The animation is fixed when it starts (tick, duration) and reads no statistics at each frame; each frame is asked for by the page's render while it runs, and none after. Structural tests check that it draws neither the grid nor the ring again, tessellates no crown, builds no card, recomputes no statistics and asks for no frame at rest, and that leaving a grid it held still sorts nothing and builds no card. - **Two splashes decoded at most**: the one shown and the one replacing it. All splashes are downloaded in the background, at low priority, after the card portraits, and kept on disk. - During champ select, the Anvil grid is cached at the height of its card rows. The capture replay checks that a splash fade builds no cards and that traversing the hand and « Autres champions » keeps at most two decoded splashes. The latest hovered card takes over when the current fade finishes. diff --git a/docs/research/arena-match-statistics.md b/docs/research/arena-match-statistics.md index a1e0ed0..1f2229e 100644 --- a/docs/research/arena-match-statistics.md +++ b/docs/research/arena-match-statistics.md @@ -4,7 +4,7 @@ Pour [#22](https://gitea.nessar.fr/nessar/arena-tracker/issues/22), ouvrir le r ## Ce que contient une Partie publiée -Le 17 novembre 2026, la lecture des réponses Riot déjà conservées dans la base locale a couvert **471 Parties distinctes et 8 162 participants**. Elles se répartissent entre les files 1700 (158 Parties), 1740 (41) et 1750 (272). Les dates de début vont du 12 décembre 2025 au 16 novembre 2026 (UTC). Les six exemples réduits du dépôt servent à vérifier la structure du Match et les Formats, mais leur sélection de champs ne permet pas de mesurer la fréquence des statistiques. [Exemples Match‑V5](../../crates/core/tests/fixtures/riot) · [Stockage du JSON source](../../crates/core/src/tracker.rs) +Le 17 novembre 2026, la lecture des réponses Riot déjà conservées dans la base locale a couvert **471 Parties distinctes et 8 162 participants**. Elles se répartissent entre les files 1700 (158 Parties), 1740 (41) et 1750 (272). Les dates de début vont du 12 décembre 2025 au 16 novembre 2026 (UTC). Les six exemples réduits du dépôt servent à vérifier la structure du Match et les Formats, mais leur sélection de champs ne permet pas de mesurer la fréquence des statistiques. [Exemples Match‑V5](../../crates/core/tests/fixtures/riot) · [Stockage du JSON source](../../crates/core/src/tracker/storage.rs) Toutes les lignes ci-dessous viennent de `GET /lol/match/v5/matches/{matchId}`, dans `info.participants[]` sauf indication contraire. Elles deviennent récupérables après publication, pendant la disponibilité de la Partie chez Riot, puis aussi longtemps que la copie locale est conservée. [Référence Match‑V5](https://developer.riotgames.com/apis#match-v5/GET_getMatch)