diff --git a/CHANGELOG.md b/CHANGELOG.md index 32582ef..6aace4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Fixed + +- **Live views got slower the longer a run lasted.** The Dashboard on every new wave, and a live run selected or compared in History every couple of seconds, reloaded every recorded row for that run. A run selected in History also redrew all of them, even after switching to another tab. They now fetch only the rows added since the last refresh. + +- **Clicking a coin/min point in select mode did nothing.** The highlight drawn on the point under the mouse was taking the click. Coin/min points can now be selected by clicking them. +- **Select mode in History could look stuck on a long run.** Turning it on froze the app for several seconds before the button even changed. That's gone with the paged tables below. Clicking a point on the chart also no longer scrolls the chart off screen, and a slightly shaky click no longer counts as a drag. +- **Dragging a rectangle on the chart could select the wrong points, or not start at all.** It worked out coin values from the run's own range rather than the chart's axis, so the selection didn't match the rectangle on any run whose coin/min stayed well above zero. Drags can now also start on top of a point. + +### Changed + +- **The coin/min, GC activation and wave skip tables in History now show 100 rows per page.** Clicking a point on the chart jumps to the page holding its row. "Select all" and the outlier selection still cover the whole run. + --- ## [0.4.24] — 2026-10-27 diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 430782c..ed2389d 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -4,7 +4,7 @@ use base64::Engine; use tauri::{AppHandle, Emitter, Manager, State}; use crate::backup::{self, BackupExport, BackupRestore}; -use crate::db::{self, RunFilter, RunRow, SnapshotRow, WaveSkipRow}; +use crate::db::{self, RunFilter, RunRow}; use crate::debug_package::{self, DebugPackageExport, DebugScreenshotInput}; use crate::export::{self, ExportFileResult}; use crate::scanner::{ScanStartMode, Scanner}; @@ -441,75 +441,9 @@ pub fn clear_snapshot_golden_combo(snapshot_ids: Vec) -> Result Result, String> { - run_blocking("run_snapshots", move || { - db::run_snapshots(&conn()?, &run_id).map_err(|e| e.to_string()) - }) - .await -} - -#[derive(Debug, Serialize)] -pub struct DashboardRunView { - pub snapshot_total: usize, - pub chart_snapshots: Vec, - pub skip_total: usize, - pub chart_wave_skips: Vec, - pub chart_normal_jumps: Vec, - pub avg_golden_combo_caret: Option, -} - -fn dashboard_run_view(run_id: &str) -> Result { - let conn = conn()?; - let (snapshot_total, chart_snapshots, chart_normal_jumps) = db::run_snapshot_chart_bundle( - &conn, - run_id, - db::CHART_SNAPSHOT_LIMIT, - db::CHART_SKIP_LIMIT, - ) - .map_err(|e| e.to_string())?; - let (skip_total, chart_wave_skips) = - db::run_wave_skips_for_chart(&conn, run_id, db::CHART_SKIP_LIMIT) - .map_err(|e| e.to_string())?; - let avg_golden_combo_caret = - db::avg_golden_combo_caret(&conn, run_id).map_err(|e| e.to_string())?; - Ok(DashboardRunView { - snapshot_total, - chart_snapshots, - skip_total, - chart_wave_skips, - chart_normal_jumps, - avg_golden_combo_caret, - }) -} - -#[tauri::command] -pub async fn current_run_dashboard( - state: State<'_, AppState>, -) -> Result { - let id = state.scanner.current_run_id.lock().unwrap().clone(); - run_blocking("current_run_dashboard", move || match id { - Some(id) => dashboard_run_view(&id), - None => Ok(DashboardRunView { - snapshot_total: 0, - chart_snapshots: Vec::new(), - skip_total: 0, - chart_wave_skips: Vec::new(), - chart_normal_jumps: Vec::new(), - avg_golden_combo_caret: None, - }), - }) - .await -} - -#[tauri::command] -pub async fn run_dashboard_data(run_id: String) -> Result { - run_blocking("run_dashboard_data", move || dashboard_run_view(&run_id)).await -} - -#[tauri::command] -pub async fn run_wave_skips(run_id: String) -> Result, String> { - run_blocking("run_wave_skips", move || { - db::run_wave_skips(&conn()?, &run_id).map_err(|e| e.to_string()) +pub async fn run_rows(run_id: String, after: db::RunRowsCursor) -> Result { + run_blocking("run_rows", move || { + db::run_rows_after(&conn()?, &run_id, after).map_err(|e| e.to_string()) }) .await } diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 43b6c9d..1d4910b 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -938,34 +938,87 @@ fn sync_run_snapshot_stats(conn: &Connection, run_id: &str) -> rusqlite::Result< Ok(()) } +fn snapshot_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(SnapshotRow { + id: row.get(0)?, + wave: row.get(1)?, + tier: row.get(2)?, + coin_per_minute: row.get(3)?, + golden_combo_chance: row.get(4)?, + golden_combo_caret: row.get(5)?, + golden_combo_multiplier: row.get(6)?, + recorded_at: row.get(7)?, + }) +} + pub fn run_snapshots(conn: &Connection, run_id: &str) -> rusqlite::Result> { let mut stmt = conn.prepare( "SELECT id, wave, tier, coin_per_minute, golden_combo_chance, golden_combo_caret, golden_combo_multiplier, recorded_at FROM snapshots WHERE run_id = ?1 ORDER BY wave ASC", )?; - let rows = stmt.query_map(params![run_id], |row| { - Ok(SnapshotRow { - id: row.get(0)?, - wave: row.get(1)?, - tier: row.get(2)?, - coin_per_minute: row.get(3)?, - golden_combo_chance: row.get(4)?, - golden_combo_caret: row.get(5)?, - golden_combo_multiplier: row.get(6)?, - recorded_at: row.get(7)?, - }) - })?; + let rows = stmt.query_map(params![run_id], snapshot_from_row)?; rows.collect() } -/// Max snapshots sent to the UI chart (avoids WebView OOM on long runs). -/// Keep in sync with `MAX_CHART_POINTS` in `src/chartData.ts`. -pub const CHART_SNAPSHOT_LIMIT: usize = 5000; +/// Where a reader of a run's rows has got to. The scanner only ever appends to these +/// tables, so "rows past this point" is all a live view needs between full loads (edits +/// and deletes are user actions, which reload in full). Rowids rather than `recorded_at`: +/// those strings have a variable number of fractional digits, so they don't compare in +/// time order. The default cursor is before every row. +#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq, Eq)] +pub struct RunRowsCursor { + pub snapshot_rowid: i64, + pub wave_skip_rowid: i64, +} + +#[derive(Debug, Serialize)] +pub struct RunRowsPage { + pub snapshots: Vec, + pub wave_skips: Vec, + pub cursor: RunRowsCursor, +} + +/// A run's snapshots and wave skips past `after`, each table ordered as `run_snapshots` +/// and `run_wave_skips` order it. +pub fn run_rows_after( + conn: &Connection, + run_id: &str, + after: RunRowsCursor, +) -> rusqlite::Result { + let mut cursor = after; + + let mut stmt = conn.prepare( + "SELECT id, wave, tier, coin_per_minute, + golden_combo_chance, golden_combo_caret, golden_combo_multiplier, recorded_at, + rowid + FROM snapshots WHERE run_id = ?1 AND rowid > ?2 ORDER BY wave ASC", + )?; + let mut snapshots = Vec::new(); + let mut rows = stmt.query(params![run_id, after.snapshot_rowid])?; + while let Some(row) = rows.next()? { + snapshots.push(snapshot_from_row(row)?); + cursor.snapshot_rowid = cursor.snapshot_rowid.max(row.get(8)?); + } + + let mut stmt = conn.prepare( + "SELECT id, at_wave, skipped_count, skip_multiplier, coin_per_minute, recorded_at, + rowid + FROM wave_skips WHERE run_id = ?1 AND rowid > ?2 ORDER BY at_wave ASC, recorded_at ASC", + )?; + let mut wave_skips = Vec::new(); + let mut rows = stmt.query(params![run_id, after.wave_skip_rowid])?; + while let Some(row) = rows.next()? { + wave_skips.push(wave_skip_from_row(row)?); + cursor.wave_skip_rowid = cursor.wave_skip_rowid.max(row.get(6)?); + } -/// Max skip markers sent to the UI chart (sampled independently of snapshots). -/// Keep in sync with `MAX_CHART_SKIPS` in `src/chartData.ts`. -pub const CHART_SKIP_LIMIT: usize = 5000; + Ok(RunRowsPage { + snapshots, + wave_skips, + cursor, + }) +} pub fn snapshot_count(conn: &Connection, run_id: &str) -> rusqlite::Result { let count: i64 = conn.query_row( @@ -976,19 +1029,6 @@ pub fn snapshot_count(conn: &Connection, run_id: &str) -> rusqlite::Result rusqlite::Result> { - conn.query_row( - "SELECT AVG(golden_combo_caret) FROM snapshots - WHERE run_id = ?1 AND golden_combo_caret IS NOT NULL", - params![run_id], - |row| row.get(0), - ) -} - /// (golden_combo_chance, golden_combo_caret, golden_combo_multiplier) type GoldenComboSnapshot = (Option, i64, Option); @@ -1020,69 +1060,15 @@ pub fn wave_skip_count(conn: &Connection, run_id: &str) -> rusqlite::Result(items: &[T], max_points: usize) -> Vec { - if items.len() <= max_points || max_points <= 1 { - return items.to_vec(); - } - let last = items.len() - 1; - (0..max_points) - .map(|i| { - let idx = (i * last) / (max_points - 1); - items[idx].clone() - }) - .collect() -} - -pub fn downsample_snapshot_rows( - rows: &[SnapshotRow], - max_points: usize, -) -> Vec { - downsample_slice(rows, max_points) -} - -pub fn downsample_wave_skip_rows( - rows: &[WaveSkipRow], - max_points: usize, -) -> Vec { - downsample_slice(rows, max_points) -} - -pub fn run_wave_skips_for_chart( - conn: &Connection, - run_id: &str, - max_points: usize, -) -> rusqlite::Result<(usize, Vec)> { - let all = run_wave_skips(conn, run_id)?; - let total = all.len(); - Ok((total, downsample_wave_skip_rows(&all, max_points))) -} - -/// +1 wave jumps from an already-fetched snapshot series (no query of its own). -fn normal_jump_waves(all: &[SnapshotRow]) -> Vec { - all.windows(2) - .filter(|w| { - let prev = w[0].wave; - let wave = w[1].wave; - wave > prev && wave - prev == 1 - }) - .map(|w| w[1].wave) - .collect() -} - -/// Snapshot total, downsampled chart points, and downsampled +1 wave-jump waves — all -/// from one query. The dashboard previously fetched the full snapshot series twice -/// (once per derived value), which got more expensive every wave on a long run. -pub fn run_snapshot_chart_bundle( - conn: &Connection, - run_id: &str, - max_snapshot_points: usize, - max_jump_points: usize, -) -> rusqlite::Result<(usize, Vec, Vec)> { - let all = run_snapshots(conn, run_id)?; - let total = all.len(); - let chart_snapshots = downsample_snapshot_rows(&all, max_snapshot_points); - let chart_normal_jumps = downsample_slice(&normal_jump_waves(&all), max_jump_points); - Ok((total, chart_snapshots, chart_normal_jumps)) +fn wave_skip_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(WaveSkipRow { + id: row.get(0)?, + at_wave: row.get(1)?, + skipped_count: row.get(2)?, + skip_multiplier: row.get(3)?, + coin_per_minute: row.get(4)?, + recorded_at: row.get(5)?, + }) } pub fn run_wave_skips(conn: &Connection, run_id: &str) -> rusqlite::Result> { @@ -1090,16 +1076,7 @@ pub fn run_wave_skips(conn: &Connection, run_id: &str) -> rusqlite::Result = (0..total as i64) - .map(|i| SnapshotRow { - id: format!("s{i}"), - wave: i, - tier: Some(1), - coin_per_minute: Some(i as f64), - golden_combo_chance: None, - golden_combo_caret: None, - golden_combo_multiplier: None, - recorded_at: "t".into(), - }) - .collect(); - let out = downsample_snapshot_rows(&rows, CHART_SNAPSHOT_LIMIT); - assert_eq!(out.len(), CHART_SNAPSHOT_LIMIT); - assert_eq!(out.first().unwrap().wave, 0); - assert_eq!(out.last().unwrap().wave, total as i64 - 1); - } - - #[test] - fn downsample_wave_skip_rows_keeps_endpoints() { - let total = CHART_SKIP_LIMIT * 2; - let rows: Vec = (0..total as i64) - .map(|i| WaveSkipRow { - id: format!("w{i}"), - at_wave: i * 10, - skipped_count: 2, - skip_multiplier: None, - coin_per_minute: None, - recorded_at: "t".into(), - }) - .collect(); - let out = downsample_wave_skip_rows(&rows, CHART_SKIP_LIMIT); - assert_eq!(out.len(), CHART_SKIP_LIMIT); - assert_eq!(out.first().unwrap().at_wave, 0); - assert_eq!(out.last().unwrap().at_wave, (total as i64 - 1) * 10); - } - - #[test] - fn normal_jump_waves_keeps_only_consecutive_plus_one_steps() { - fn snap(wave: i64) -> SnapshotRow { - SnapshotRow { - id: format!("s{wave}"), - wave, - tier: None, - coin_per_minute: None, - golden_combo_chance: None, - golden_combo_caret: None, - golden_combo_multiplier: None, - recorded_at: "t".into(), - } - } - // 1->2 is a +1 jump; 2->5 is a skip, not a normal jump. - let rows = vec![snap(1), snap(2), snap(5)]; - assert_eq!(normal_jump_waves(&rows), vec![2]); + fn run_rows_after_returns_only_rows_past_the_cursor() { + let conn = open_in_memory().unwrap(); + let run_id = start_run(&conn, "farming").unwrap(); + let other_run = start_run(&conn, "farming").unwrap(); + insert_snapshot(&conn, &run_id, 1, None, None, None, None, None).unwrap(); + insert_snapshot(&conn, &run_id, 2, None, None, None, None, None).unwrap(); + insert_wave_skip(&conn, &run_id, 2, 1, None, None).unwrap(); + insert_snapshot(&conn, &other_run, 9, None, None, None, None, None).unwrap(); + + let first = run_rows_after(&conn, &run_id, RunRowsCursor::default()).unwrap(); + assert_eq!(first.snapshots.len(), 2); + assert_eq!(first.wave_skips.len(), 1); + + let none_new = run_rows_after(&conn, &run_id, first.cursor).unwrap(); + assert!(none_new.snapshots.is_empty() && none_new.wave_skips.is_empty()); + assert_eq!(none_new.cursor, first.cursor); + + insert_snapshot(&conn, &run_id, 3, None, None, None, None, None).unwrap(); + insert_wave_skip(&conn, &run_id, 3, 1, None, None).unwrap(); + let added = run_rows_after(&conn, &run_id, first.cursor).unwrap(); + assert_eq!(added.snapshots.iter().map(|s| s.wave).collect::>(), [3]); + assert_eq!(added.wave_skips.iter().map(|s| s.at_wave).collect::>(), [3]); } #[test] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dc7dd6f..a99e0c8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -174,10 +174,7 @@ pub fn run() { commands::delete_wave_skips, commands::delete_wave_skip, commands::combine_runs, - commands::run_snapshots, - commands::current_run_dashboard, - commands::run_dashboard_data, - commands::run_wave_skips, + commands::run_rows, commands::export_csv, commands::export_workbook, commands::export_backup, diff --git a/src/api.ts b/src/api.ts index 5f32163..fe02c2e 100644 --- a/src/api.ts +++ b/src/api.ts @@ -132,6 +132,24 @@ export interface SnapshotRow { recorded_at: string; } +/** Where a reader of a run's append-only rows has got to (see `RunRowsCursor` in db.rs). */ +export interface RunRowsCursor { + snapshot_rowid: number; + wave_skip_rowid: number; +} + +/** Before every row: asking for rows after this loads the whole run. */ +export const START_OF_RUN_ROWS: RunRowsCursor = { + snapshot_rowid: 0, + wave_skip_rowid: 0, +}; + +export interface RunRowsPage { + snapshots: SnapshotRow[]; + wave_skips: WaveSkipRow[]; + cursor: RunRowsCursor; +} + export interface WaveSkipRow { id: string; at_wave: number; @@ -141,16 +159,6 @@ export interface WaveSkipRow { recorded_at: string; } -/** Chart-safe payload (snapshots and skips downsampled independently on the Rust side). */ -export interface DashboardRunView { - snapshot_total: number; - chart_snapshots: SnapshotRow[]; - skip_total: number; - chart_wave_skips: WaveSkipRow[]; - chart_normal_jumps: number[]; - avg_golden_combo_caret: number | null; -} - export interface RunFilter { run_type?: string; min_wave?: number; @@ -319,13 +327,8 @@ export const api = { invoke("delete_wave_skip", { waveSkipId }), combineRuns: (runIds: string[]) => invoke("combine_runs", { runIds }), - runSnapshots: (runId: string) => - invoke("run_snapshots", { runId }), - currentRunDashboard: () => invoke("current_run_dashboard"), - runDashboardData: (runId: string) => - invoke("run_dashboard_data", { runId }), - runWaveSkips: (runId: string) => - invoke("run_wave_skips", { runId }), + runRows: (runId: string, after: RunRowsCursor) => + invoke("run_rows", { runId, after }), exportCsv: (filter: RunFilter) => invoke("export_csv", { filter }), exportWorkbook: (filter: RunFilter) => diff --git a/src/chartData.test.ts b/src/chartData.test.ts index 9477df1..9b02b8f 100644 --- a/src/chartData.test.ts +++ b/src/chartData.test.ts @@ -73,12 +73,6 @@ describe("snapshotsToChartData", () => { const points = snapshotsToChartData(snapshots); expect(points.map((p) => p.wave)).toEqual([2, 3]); }); - - it("skips re-downsampling when alreadySampled is set", () => { - const snapshots = Array.from({ length: 6000 }, (_, i) => snapshot(i, i)); - const points = snapshotsToChartData(snapshots, { alreadySampled: true }); - expect(points).toHaveLength(6000); - }); }); describe("averageGoldenComboCaret", () => { diff --git a/src/chartData.ts b/src/chartData.ts index 4fd9ee8..defd466 100644 --- a/src/chartData.ts +++ b/src/chartData.ts @@ -7,12 +7,9 @@ export type CoinChartPoint = { golden_combo_caret: number | null; }; -/** Keep Recharts responsive during very long runs. Sync with `CHART_SNAPSHOT_LIMIT` in `src-tauri/src/db.rs`. */ +/** Keep Recharts responsive during very long runs. */ export const MAX_CHART_POINTS = 5000; -/** Skip-axis cap; sampled independently of snapshots. Sync with `CHART_SKIP_LIMIT` in `src-tauri/src/db.rs`. */ -export const MAX_CHART_SKIPS = 5000; - export function downsampleChartData( points: CoinChartPoint[], maxPoints = MAX_CHART_POINTS @@ -98,10 +95,7 @@ export type WaveSkipMarker = { skip_tooltip: string; }; -export function snapshotsToChartData( - snapshots: SnapshotRow[], - options?: { alreadySampled?: boolean } -): CoinChartPoint[] { +export function snapshotsToChartData(snapshots: SnapshotRow[]): CoinChartPoint[] { const points = snapshots .filter( (s) => s.coin_per_minute !== null || s.golden_combo_caret !== null @@ -111,7 +105,7 @@ export function snapshotsToChartData( coin: s.coin_per_minute, golden_combo_caret: s.golden_combo_caret, })); - return options?.alreadySampled ? points : downsampleChartData(points); + return downsampleChartData(points); } /** Average Golden Combo activation count (^N) across snapshots that have it. */ @@ -140,28 +134,7 @@ function markerFromSkipRow(row: WaveSkipRow): WaveSkipMarker { } /** Chart markers from independently sampled skip rows and +1 jump waves. */ -export function buildChartWaveJumpMarkers( - waveSkips: WaveSkipRow[], - normalJumpWaves: number[] = [] -): WaveSkipMarker[] { - const skipByWave = new Map(waveSkips.map((row) => [row.at_wave, row])); - const markers: WaveSkipMarker[] = waveSkips.map(markerFromSkipRow); - - for (const wave of normalJumpWaves) { - if (!skipByWave.has(wave)) { - markers.push({ - id: `wave-jump-${wave}`, - wave, - skip_count: 1, - skip_tooltip: "1", - }); - } - } - - return markers.sort((a, b) => a.wave - b.wave); -} - -/** Chart markers from full snapshot/skip data (History tables). */ +/** Chart markers from a run's snapshot and skip rows. */ export function buildWaveJumpMarkers( snapshots: SnapshotRow[], waveSkips: WaveSkipRow[] = [] diff --git a/src/components/CoinVsWaveChart.tsx b/src/components/CoinVsWaveChart.tsx index 6ffe2ed..d9d9998 100644 --- a/src/components/CoinVsWaveChart.tsx +++ b/src/components/CoinVsWaveChart.tsx @@ -76,6 +76,11 @@ export type ChartLineConfig = { const SKIP_AXIS_MAX = 20; const SKIP_DOT_R = 3; +/** Invisible click target around a dot. Dots of different series overlap on a dense run + * and the top one takes the click, so this can't be much wider than a dot. */ +const DOT_HIT_R = 8; +/** Pointer travel that turns a press into a drag; a click often moves a pixel or two. */ +const DRAG_THRESHOLD_PX = 4; const COIN_LINE_COLOR = "#4cc2ff"; const GC_LINE_COLOR = "#6ec6a0"; const SKIP_LINE_COLOR = "#e8b339"; @@ -101,9 +106,7 @@ function createSkipDot( { - if (!clickable) return; - e.stopPropagation(); - e.preventDefault(); + if (clickable) e.preventDefault(); }} onClick={(e) => { if (!clickable || !skipId) return; @@ -112,8 +115,7 @@ function createSkipDot( onSkipClick?.(skipId, payload.wave); }} > - {/* Hit target above the coin line; keep large for easy select-mode clicks. */} - + { - if (!clickable) return; - e.stopPropagation(); - e.preventDefault(); + if (clickable) e.preventDefault(); }} onClick={(e) => { if (!clickable) return; @@ -165,7 +165,7 @@ function createGcDot( onGcClick?.(wave); }} > - + number }; + type SelectionBox = { waveMin: number; waveMax: number; @@ -423,7 +425,13 @@ function SingleRunChart({ buckets, }: SingleProps & { buckets: number }) { const layoutRef = useRef(null); - const dragRef = useRef<{ wave: number; coin: number } | null>(null); + const scalesRef = useRef<{ wave?: InvertibleScale; coin?: InvertibleScale }>({}); + const dragRef = useRef<{ + wave: number; + coin: number; + chartX: number; + chartY: number; + } | null>(null); const draggedRef = useRef(false); const suppressClickRef = useRef(false); const [selectionBox, setSelectionBox] = useState(null); @@ -432,36 +440,22 @@ function SingleRunChart({ const selectedGcSet = new Set(selectedGcWaves); const selectable = !!onSelectWaves; - const bounds = useMemo(() => { - const waves = data.map((d) => d.wave); - const coins = data - .map((d) => d.coin) - .filter((c): c is number => c != null && Number.isFinite(c)); - return { - waveMin: Math.min(...waves), - waveMax: Math.max(...waves), - coinMin: coins.length ? Math.min(...coins) : 0, - coinMax: coins.length ? Math.max(...coins) : 1, - }; - }, [data]); - + // Through the axes' own scales: the coin axis starts at 0 and rounds up, so it isn't the + // data's range, and a rectangle mapped onto that range selected the wrong points. const pointerToData = useCallback( (chartX?: number, chartY?: number): { wave: number; coin: number } | null => { const layout = layoutRef.current; - if (!layout || chartX == null || chartY == null) return null; + const { wave, coin } = scalesRef.current; + if (!layout || !wave?.invert || !coin?.invert) return null; + if (chartX == null || chartY == null) return null; const { left, top, width, height: plotHeight } = layout; if (width <= 0 || plotHeight <= 0) return null; - - const waveSpan = bounds.waveMax - bounds.waveMin || 1; - const coinSpan = bounds.coinMax - bounds.coinMin || 1; - const tx = clamp((chartX - left) / width, 0, 1); - const ty = clamp((chartY - top) / plotHeight, 0, 1); return { - wave: bounds.waveMin + tx * waveSpan, - coin: bounds.coinMax - ty * coinSpan, + wave: wave.invert(clamp(chartX, left, left + width)), + coin: coin.invert(clamp(chartY, top, top + plotHeight)), }; }, - [bounds] + [] ); const updateSelectionBox = useCallback( @@ -492,30 +486,27 @@ function SingleRunChart({ [data] ); - const handleMouseDown = (state: ChartMouseState, event: MouseEvent) => { - if (!selectable) return; - const target = event.target as SVGElement; - const tag = target.tagName?.toLowerCase(); - if (tag === "circle") return; + const handleMouseDown = (state: ChartMouseState) => { + suppressClickRef.current = false; + if (!selectable || state?.chartX == null || state.chartY == null) return; const point = pointerToData(state.chartX, state.chartY); if (!point) return; - dragRef.current = point; + dragRef.current = { ...point, chartX: state.chartX, chartY: state.chartY }; draggedRef.current = false; - updateSelectionBox(point, point); }; const handleMouseMove = (state: ChartMouseState) => { const start = dragRef.current; - if (!start || !selectable) return; + if (!start || !selectable || state?.chartX == null || state.chartY == null) return; const point = pointerToData(state.chartX, state.chartY); if (!point) return; if ( - Math.abs(point.wave - start.wave) > 0.01 || - Math.abs(point.coin - start.coin) > 0.01 + Math.hypot(state.chartX - start.chartX, state.chartY - start.chartY) >= + DRAG_THRESHOLD_PX ) { draggedRef.current = true; } - updateSelectionBox(start, point); + if (draggedRef.current) updateSelectionBox(start, point); }; const finishDrag = (additive: boolean) => { @@ -542,9 +533,14 @@ function SingleRunChart({ const handleChartClick = () => { // Selection is handled only by per-series dots. Chart-level clicks used to // always pick coin/min and stole GC / jump clicks in select mode. - if (suppressClickRef.current) { - suppressClickRef.current = false; - } + suppressClickRef.current = false; + }; + + /** True for the click a drag ends with when it's released on the dot it started on. */ + const consumeDragClick = () => { + const wasDrag = suppressClickRef.current; + suppressClickRef.current = false; + return wasDrag; }; // What gets drawn is thinned to the chart's pixel width (see `downsampleForWidth`); @@ -618,10 +614,18 @@ function SingleRunChart({ onClick={handleChartClick} > { + component={(props: { + offset?: PlotOffset; + xAxisMap?: Record; + yAxisMap?: Record; + }) => { if (props.offset) { layoutRef.current = props.offset; } + scalesRef.current = { + wave: Object.values(props.xAxisMap ?? {})[0]?.scale, + coin: props.yAxisMap?.coin?.scale, + }; return null; }} /> @@ -739,18 +743,16 @@ function SingleRunChart({ key={wave} style={{ cursor: showDots ? "pointer" : undefined }} onMouseDown={(e) => { - if (!showDots) return; - e.stopPropagation(); - e.preventDefault(); + if (showDots) e.preventDefault(); }} onClick={(e) => { if (!showDots) return; e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); - onPointClick?.(wave); + if (!consumeDragClick()) onPointClick?.(wave); }} > - + { + if (!consumeDragClick()) onSkipClick(id, wave); + }) : false } activeDot={false} @@ -805,7 +810,9 @@ function SingleRunChart({ isAnimationActive={false} dot={ onGcClick - ? createGcDot(GC_LINE_COLOR, selectedGcSet, onGcClick) + ? createGcDot(GC_LINE_COLOR, selectedGcSet, (wave) => { + if (!consumeDragClick()) onGcClick(wave); + }) : false } activeDot={false} diff --git a/src/components/Dashboard.tsx b/src/components/Dashboard.tsx index aa79b1b..5bfb075 100644 --- a/src/components/Dashboard.tsx +++ b/src/components/Dashboard.tsx @@ -4,13 +4,19 @@ import { formatCoin, formatGoldenComboMultiplier, ScannerEvent, - SnapshotRow, - WaveSkipRow, } from "../api"; import { + MAX_CHART_POINTS, snapshotsToChartData, - buildChartWaveJumpMarkers, + buildWaveJumpMarkers, } from "../chartData"; +import { + DATA_RESTORED_EVENT, + EMPTY_RUN_ROWS, + RUN_ROWS_EDITED_EVENT, + RunRowsReader, + type RunRows, +} from "../runRows"; import { formatSkipLiveStat, } from "../skipDisplay"; @@ -23,11 +29,7 @@ import { CoinIcon, WaveJumpIcon, GcActivationIcon } from "./ChartToggleIcons"; const SNAPSHOT_REFRESH_MS = 15_000; export default function Dashboard({ event }: { event: ScannerEvent | null }) { - const [snapshotTotal, setSnapshotTotal] = useState(0); - const [chartSnapshots, setChartSnapshots] = useState([]); - const [skipTotal, setSkipTotal] = useState(0); - const [chartWaveSkips, setChartWaveSkips] = useState([]); - const [chartNormalJumps, setChartNormalJumps] = useState([]); + const [rows, setRows] = useState(EMPTY_RUN_ROWS); const [showWaveJumps, setShowWaveJumps] = usePersistedBoolean( "dashboard.showWaveJumps", true @@ -41,65 +43,57 @@ export default function Dashboard({ event }: { event: ScannerEvent | null }) { true ); const chartRef = useRef(null); - const lastFetchAtRef = useRef(0); - const lastWaveRef = useRef(null); - const liveWaveRef = useRef(null); - liveWaveRef.current = event?.live?.wave ?? null; const live = event?.live ?? null; + const runId = event?.current_run_id ?? null; useEffect(() => { - // Guards against a new fetch starting while a previous one is still in flight — the - // wave-changed/staleness checks below bound how *often* a fetch is considered, but not - // whether the last one actually finished. Once currentRunDashboard() takes longer than - // the gap between scanner ticks (a growing snapshots table gets there eventually) and the - // wave is changing every tick anyway, calls piled up unbounded with no cap at all. - let inFlight = false; - const refresh = (force = false) => { - const wave = liveWaveRef.current; - const now = Date.now(); - const waveChanged = wave !== null && wave !== lastWaveRef.current; - const stale = now - lastFetchAtRef.current >= SNAPSHOT_REFRESH_MS; - if (!force && !waveChanged && !stale && lastFetchAtRef.current > 0) { - return; - } - if (inFlight) return; - inFlight = true; - lastFetchAtRef.current = now; - lastWaveRef.current = wave; - api - .currentRunDashboard() - .then((view) => { - setSnapshotTotal(view.snapshot_total); - setChartSnapshots(view.chart_snapshots); - setSkipTotal(view.skip_total); - setChartWaveSkips(view.chart_wave_skips); - setChartNormalJumps(view.chart_normal_jumps); - }) - .catch(() => {}) - .finally(() => { - inFlight = false; - }); + if (!runId) { + setRows(EMPTY_RUN_ROWS); + return; + } + let active = true; + const reader = new RunRowsReader(runId); + const show = (next: RunRows | null) => { + if (active && next) setRows(next); + }; + const reload = () => { + reader.load().then(show).catch(() => {}); }; - lastFetchAtRef.current = 0; - lastWaveRef.current = null; - refresh(true); + let lastFetchAt = Date.now(); + let lastWave: number | null = null; + const refresh = (e: ScannerEvent) => { + const wave = e.live?.wave ?? null; + const now = Date.now(); + const waveChanged = wave !== null && wave !== lastWave; + if (!waveChanged && now - lastFetchAt < SNAPSHOT_REFRESH_MS) return; + lastFetchAt = now; + lastWave = wave; + reader.readNew().then(show).catch(() => {}); + }; + reload(); let unlisten: (() => void) | undefined; - void api.onScannerUpdate(() => refresh()).then((fn) => { - unlisten = fn; + void api.onScannerUpdate(refresh).then((fn) => { + if (active) unlisten = fn; + else fn(); }); - return () => unlisten?.(); - }, [event?.current_run_id]); + window.addEventListener(RUN_ROWS_EDITED_EVENT, reload); + window.addEventListener(DATA_RESTORED_EVENT, reload); + return () => { + active = false; + unlisten?.(); + window.removeEventListener(RUN_ROWS_EDITED_EVENT, reload); + window.removeEventListener(DATA_RESTORED_EVENT, reload); + }; + }, [runId]); - const chartData = useMemo( - () => snapshotsToChartData(chartSnapshots, { alreadySampled: true }), - [chartSnapshots] - ); + const chartData = useMemo(() => snapshotsToChartData(rows.snapshots), [rows.snapshots]); const skipMarkers = useMemo( - () => buildChartWaveJumpMarkers(chartWaveSkips, chartNormalJumps), - [chartWaveSkips, chartNormalJumps] + () => buildWaveJumpMarkers(rows.snapshots, rows.wave_skips), + [rows.snapshots, rows.wave_skips] ); + const snapshotTotal = rows.snapshots.length; const lastSkipDisplay = live?.last_wave_delta != null ? live.last_skip_multiplier != null @@ -160,10 +154,9 @@ export default function Dashboard({ event }: { event: ScannerEvent | null }) {

Coin/min vs Wave (current run)

{snapshotTotal} snapshot{snapshotTotal === 1 ? "" : "s"} this run - {snapshotTotal > chartSnapshots.length && - ` · chart shows ${chartSnapshots.length} sampled snapshot points`} - {skipTotal > chartWaveSkips.length && - ` · ${chartWaveSkips.length} of ${skipTotal} skips sampled for chart`} + {chartData.length === MAX_CHART_POINTS && + snapshotTotal > MAX_CHART_POINTS && + ` · chart shows ${MAX_CHART_POINTS} sampled snapshot points`} {" · saved automatically — every run's chart stays in History"} diff --git a/src/components/History.tsx b/src/components/History.tsx index ccdb753..2264ff8 100644 --- a/src/components/History.tsx +++ b/src/components/History.tsx @@ -13,7 +13,6 @@ import { applyCompareChartSmoothing, compareNewerRunIndex, compareHasGoldenComboActivations, - buildChartWaveJumpMarkers, buildWaveJumpMarkers, mergeCompareWithSkips, snapshotsToChartData, @@ -23,6 +22,14 @@ import ChartScreenshotActions from "./ChartScreenshotActions"; import CoinVsWaveChart, { ChartLineConfig } from "./CoinVsWaveChart"; import SkipCoinAnalytics from "./SkipCoinAnalytics"; import SortableTh from "./SortableTh"; +import TablePager from "./TablePager"; +import { useTablePage } from "../tablePage"; +import { + DATA_RESTORED_EVENT, + RUN_ROWS_EDITED_EVENT, + RunRowsReader, + type RunRows, +} from "../runRows"; import { formatSkipDisplay, skipDisplayFromRow, skipChartValue } from "../skipDisplay"; import { formatRunType, runTypeUsesBadge, RUN_TYPE_FILTER_OPTIONS } from "../runType"; import { reportUiError } from "../uiError"; @@ -108,6 +115,20 @@ const PAGE_SIZES = [5, 10, 25, 50, 100] as const; /** Min gap between live History table refreshes on scanner-update (avoids DB thrash). */ const LIVE_REFRESH_MIN_MS = 2500; +/** A fresh, fully loaded reader per run. */ +async function loadCompareReaders(ids: string[]) { + const readers = new Map(ids.map((id) => [id, new RunRowsReader(id)])); + await Promise.all([...readers.values()].map((reader) => reader.load())); + return readers; +} + +function toggledInSet(prev: Set, id: string): Set { + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; +} + function pruneSelectedIds( prev: Set, validIds: Iterable @@ -242,9 +263,6 @@ function History() { const [checked, setChecked] = useState>(new Set()); const [snapshots, setSnapshots] = useState([]); const [waveSkips, setWaveSkips] = useState([]); - const [liveChartSnapshots, setLiveChartSnapshots] = useState([]); - const [liveChartWaveSkips, setLiveChartWaveSkips] = useState([]); - const [liveChartNormalJumps, setLiveChartNormalJumps] = useState([]); const [compareRuns, setCompareRuns] = useState([]); const [compareSnapshots, setCompareSnapshots] = useState< Record @@ -252,9 +270,6 @@ function History() { const [compareWaveSkips, setCompareWaveSkips] = useState< Record >({}); - const [compareNormalJumps, setCompareNormalJumps] = useState< - Record - >({}); const [compareLoading, setCompareLoading] = useState(false); const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(5); @@ -330,9 +345,11 @@ function History() { } | null>(null); const chartRef = useRef(null); const compareChartRef = useRef(null); - const snapshotRowRefs = useRef>(new Map()); - const waveSkipRowRefs = useRef>(new Map()); - const gcRowRefs = useRef>(new Map()); + /** Reads the selected run's rows; replaced whenever the selection changes. */ + const runReaderRef = useRef(null); + /** Reads the compared runs' rows; replaced whole whenever the comparison is loaded, so a + * refresh can tell its readers have been superseded. */ + const compareReadersRef = useRef>(new Map()); const liveRefreshAtRef = useRef(0); /** Same in-flight guard as compareRefreshInFlightRef, for refreshSelectedRun()'s own * triggers — the scanner-tick one already has a time-based throttle, but that only bounds @@ -583,22 +600,36 @@ function History() { } }, [reload]); + const showRunRows = useCallback((reader: RunRowsReader, rows: RunRows | null) => { + if (!rows || runReaderRef.current !== reader) return; + setSnapshots(rows.snapshots); + setWaveSkips(rows.wave_skips); + }, []); + + const showCompareRows = useCallback((readers: Map) => { + compareReadersRef.current = readers; + const entries = [...readers.entries()]; + setCompareSnapshots( + Object.fromEntries(entries.map(([id, reader]) => [id, reader.rows.snapshots])) + ); + setCompareWaveSkips( + Object.fromEntries(entries.map(([id, reader]) => [id, reader.rows.wave_skips])) + ); + }, []); + useEffect(() => { const runId = selected?.id ?? null; - if (runId) { - Promise.all([api.runSnapshots(runId), api.runWaveSkips(runId)]) - .then(([snaps, skips]) => { - setSnapshots(snaps); - setWaveSkips(skips); - }) + const reader = runId ? new RunRowsReader(runId) : null; + runReaderRef.current = reader; + if (reader) { + reader + .load() + .then((rows) => showRunRows(reader, rows)) .catch(() => {}); } else { setSnapshots([]); setWaveSkips([]); } - setLiveChartSnapshots([]); - setLiveChartWaveSkips([]); - setLiveChartNormalJumps([]); setChartSelectMode(false); setSelectedSnapshotIds(new Set()); setSelectedWaveSkipIds(new Set()); @@ -610,10 +641,25 @@ function History() { setGcOutlierAbove(""); setSkipOutlierBelow(""); setSkipOutlierAbove(""); - snapshotRowRefs.current.clear(); - waveSkipRowRefs.current.clear(); - gcRowRefs.current.clear(); - }, [selected?.id]); + }, [selected?.id, showRunRows]); + + useEffect(() => { + const onRestored = () => { + const reader = runReaderRef.current; + reader + ?.load() + .then((rows) => showRunRows(reader, rows)) + .catch(() => {}); + const readers = compareReadersRef.current; + void Promise.all([...readers.values()].map((r) => r.load())) + .then(() => { + if (compareReadersRef.current === readers) showCompareRows(readers); + }) + .catch(() => {}); + }; + window.addEventListener(DATA_RESTORED_EVENT, onRestored); + return () => window.removeEventListener(DATA_RESTORED_EVENT, onRestored); + }, [showRunRows, showCompareRows]); const sorted = sortByValue(runs, (r) => runSortValue(r, sortKey), sortAsc); @@ -695,25 +741,12 @@ function History() { const requestId = ++compareRequestRef.current; setCompareLoading(true); try { - const entries = await Promise.all( - ids.map(async (id) => { - const view = await api.runDashboardData(id); - return [id, view] as const; - }) - ); + const readers = await loadCompareReaders(ids); // A newer compareSelected()/refreshCompare() call started while this one // was in flight (e.g. re-selecting runs and clicking Compare again before // the first fetch finished) — its result already won, so drop this one. if (compareRequestRef.current !== requestId) return; - setCompareSnapshots( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_snapshots])) - ); - setCompareWaveSkips( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_wave_skips])) - ); - setCompareNormalJumps( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_normal_jumps])) - ); + showCompareRows(readers); setCompareRuns(runsToCompare); savePersistedCompareIds(runsToCompare.map((r) => r.id)); } catch (e) { @@ -739,33 +772,24 @@ function History() { const idsAtStart = compareRunIdsKey; const ids = idsAtStart ? idsAtStart.split(",") : []; if (ids.length < 2) return; + const readers = compareReadersRef.current; + // The set of compared runs changed (new comparison started, or + // cleared) while this refresh was in flight — don't clobber it. + const superseded = () => + compareRunIdsRef.current !== idsAtStart || compareReadersRef.current !== readers; try { - const [entries, tableRuns] = await Promise.all([ - Promise.all( - ids.map(async (id) => { - const view = await api.runDashboardData(id); - return [id, view] as const; - }) - ), - api.listRuns(listFilter()), - ]); + const added = await Promise.all( + ids.map((id) => readers.get(id)?.readNew() ?? null) + ); + if (superseded()) return; + if (added.some((rows) => rows != null)) showCompareRows(readers); + const tableRuns = await api.listRuns(listFilter()); // The compared runs must be found regardless of the table's active filter (they // may no longer match it) — only fetch the unfiltered list when one is missing. const allRuns = ids.every((id) => tableRuns.some((r) => r.id === id)) ? tableRuns : await api.listRuns({}); - // The set of compared runs changed (new comparison started, or - // cleared) while this refresh was in flight — don't clobber it. - if (compareRunIdsRef.current !== idsAtStart) return; - setCompareSnapshots( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_snapshots])) - ); - setCompareWaveSkips( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_wave_skips])) - ); - setCompareNormalJumps( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_normal_jumps])) - ); + if (superseded()) return; const matchedRuns = ids .map((id) => allRuns.find((r) => r.id === id)) .filter((r): r is RunRow => r != null); @@ -775,7 +799,7 @@ function History() { } catch { /* keep last chart */ } - }, [compareRunIdsKey, listFilter]); + }, [compareRunIdsKey, listFilter, showCompareRows]); const restoreCompareFromIds = useCallback( async (ids: string[]) => { @@ -783,13 +807,8 @@ function History() { const requestId = ++compareRequestRef.current; setCompareLoading(true); try { - const [entries, updatedRuns] = await Promise.all([ - Promise.all( - ids.map(async (id) => { - const view = await api.runDashboardData(id); - return [id, view] as const; - }) - ), + const [readers, updatedRuns] = await Promise.all([ + loadCompareReaders(ids), api.listRuns(listFilter()), ]); if (compareRequestRef.current !== requestId) return; @@ -802,15 +821,7 @@ function History() { savePersistedCompareIds([]); return; } - setCompareSnapshots( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_snapshots])) - ); - setCompareWaveSkips( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_wave_skips])) - ); - setCompareNormalJumps( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_normal_jumps])) - ); + showCompareRows(readers); setCompareRuns(matchedRuns); setChecked(new Set(matchedRuns.map((r) => r.id))); } catch { @@ -823,7 +834,7 @@ function History() { setCompareLoading(false); } }, - [listFilter] + [listFilter, showCompareRows] ); useEffect(() => { @@ -878,13 +889,8 @@ function History() { async (keepId: string, newRunId: string) => { const requestId = ++compareRequestRef.current; try { - const [entries, allRuns] = await Promise.all([ - Promise.all( - [keepId, newRunId].map(async (id) => { - const view = await api.runDashboardData(id); - return [id, view] as const; - }) - ), + const [readers, allRuns] = await Promise.all([ + loadCompareReaders([keepId, newRunId]), api.listRuns({}), ]); if (compareRequestRef.current !== requestId) return; @@ -898,15 +904,7 @@ function History() { // current comparison alone rather than risk clearing it. return; } - setCompareSnapshots( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_snapshots])) - ); - setCompareWaveSkips( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_wave_skips])) - ); - setCompareNormalJumps( - Object.fromEntries(entries.map(([id, view]) => [id, view.chart_normal_jumps])) - ); + showCompareRows(readers); setCompareRuns(matchedRuns); setChecked(new Set(matchedRuns.map((r) => r.id))); savePersistedCompareIds(matchedRuns.map((r) => r.id)); @@ -915,7 +913,7 @@ function History() { // update retry. } }, - [] + [showCompareRows] ); // A genuinely new pair to compare — reset which side "Follow new run" is watching so a @@ -967,7 +965,7 @@ function History() { setCompareRuns([]); setCompareSnapshots({}); setCompareWaveSkips({}); - setCompareNormalJumps({}); + compareReadersRef.current = new Map(); savePersistedCompareIds([]); }; @@ -1100,6 +1098,22 @@ function History() { [waveSkips, skipSortKey, skipSortAsc] ); + const snapshotPage = useTablePage( + sortedSnapshots, + `${selected?.id}|${coinSortKey}|${coinSortAsc}` + ); + const gcPage = useTablePage( + sortedGcSnapshots, + `${selected?.id}|${gcSortKey}|${gcSortAsc}` + ); + const waveSkipPage = useTablePage( + sortedWaveSkips, + `${selected?.id}|${skipSortKey}|${skipSortAsc}` + ); + const revealSnapshot = snapshotPage.reveal; + const revealGc = gcPage.reveal; + const revealWaveSkip = waveSkipPage.reveal; + const selectedGcWaves = useMemo( () => gcSnapshots @@ -1128,26 +1142,18 @@ function History() { snapshots.length > 0 && snapshots.every((s) => selectedSnapshotIds.has(s.id)); - const toggleSnapshotId = useCallback((id: string, wave: number) => { - setSelectedSnapshotIds((prev) => { - const next = new Set(prev); - if (next.has(id)) { - next.delete(id); - } else { - next.add(id); - snapshotRowRefs.current.get(wave)?.scrollIntoView({ - block: "nearest", - behavior: "smooth", - }); - } - return next; - }); - }, []); + const toggleSnapshotId = useCallback( + (id: string) => { + if (!selectedSnapshotIds.has(id)) revealSnapshot(id); + setSelectedSnapshotIds((prev) => toggledInSet(prev, id)); + }, + [selectedSnapshotIds, revealSnapshot] + ); const toggleSnapshotWave = useCallback( (wave: number) => { const snap = snapshotByWave.get(wave); - if (snap) toggleSnapshotId(snap.id, wave); + if (snap) toggleSnapshotId(snap.id); }, [snapshotByWave, toggleSnapshotId] ); @@ -1182,37 +1188,21 @@ function History() { setSelectedGcIds(new Set()); }; - const toggleWaveSkipId = useCallback((id: string) => { - setSelectedWaveSkipIds((prev) => { - const next = new Set(prev); - if (next.has(id)) { - next.delete(id); - } else { - next.add(id); - waveSkipRowRefs.current.get(id)?.scrollIntoView({ - block: "nearest", - behavior: "smooth", - }); - } - return next; - }); - }, []); + const toggleWaveSkipId = useCallback( + (id: string) => { + if (!selectedWaveSkipIds.has(id)) revealWaveSkip(id); + setSelectedWaveSkipIds((prev) => toggledInSet(prev, id)); + }, + [selectedWaveSkipIds, revealWaveSkip] + ); - const toggleGcId = useCallback((id: string) => { - setSelectedGcIds((prev) => { - const next = new Set(prev); - if (next.has(id)) { - next.delete(id); - } else { - next.add(id); - gcRowRefs.current.get(id)?.scrollIntoView({ - block: "nearest", - behavior: "smooth", - }); - } - return next; - }); - }, []); + const toggleGcId = useCallback( + (id: string) => { + if (!selectedGcIds.has(id)) revealGc(id); + setSelectedGcIds((prev) => toggledInSet(prev, id)); + }, + [selectedGcIds, revealGc] + ); const toggleGcWave = useCallback( (wave: number) => { @@ -1359,80 +1349,45 @@ function History() { selected != null && !selected.ended_at && compareRuns.length < 2; const refreshSelectedRun = useCallback(async (reloadTable = false) => { - if (!selectedRunId) return; + const reader = runReaderRef.current; + if (!selectedRunId || reader?.runId !== selectedRunId) return; try { const activeFilter = listFilter(); if (reloadTable || !hasOngoingSelectedRun) { - const [snaps, skips, updatedRuns] = await Promise.all([ - api.runSnapshots(selectedRunId), - api.runWaveSkips(selectedRunId), - api.listRuns(activeFilter), - ]); - setSnapshots(snaps); - setWaveSkips(skips); - setLiveChartSnapshots([]); - setLiveChartWaveSkips([]); - setLiveChartNormalJumps([]); - setSelectedSnapshotIds((prev) => - pruneSelectedIds( - prev, - snaps.map((s) => s.id) - ) - ); - setSelectedWaveSkipIds((prev) => - pruneSelectedIds( - prev, - skips.map((s) => s.id) - ) - ); - setSelectedGcIds((prev) => - pruneSelectedIds( - prev, - snaps.filter(snapshotHasGoldenCombo).map((s) => s.id) - ) - ); - setRuns(updatedRuns); - setSelected(updatedRuns.find((r) => r.id === selectedRunId) ?? null); - return; + if (reloadTable) window.dispatchEvent(new Event(RUN_ROWS_EDITED_EVENT)); + const rows = await reader.load(); + showRunRows(reader, rows); + if (rows) { + setSelectedSnapshotIds((prev) => + pruneSelectedIds( + prev, + rows.snapshots.map((s) => s.id) + ) + ); + setSelectedWaveSkipIds((prev) => + pruneSelectedIds( + prev, + rows.wave_skips.map((s) => s.id) + ) + ); + setSelectedGcIds((prev) => + pruneSelectedIds( + prev, + rows.snapshots.filter(snapshotHasGoldenCombo).map((s) => s.id) + ) + ); + } + } else { + // Ongoing run: rows are only ever added here, so selections can't go stale. + showRunRows(reader, await reader.readNew()); } - - // Ongoing run: keep chart on sampled dashboard payload; refresh full tables - // so coin/min, GC, and jump rows appear as the scanner writes them. - const [view, snaps, skips, updatedRuns] = await Promise.all([ - api.runDashboardData(selectedRunId), - api.runSnapshots(selectedRunId), - api.runWaveSkips(selectedRunId), - api.listRuns(activeFilter), - ]); - setLiveChartSnapshots(view.chart_snapshots); - setLiveChartWaveSkips(view.chart_wave_skips); - setLiveChartNormalJumps(view.chart_normal_jumps); - setSnapshots(snaps); - setWaveSkips(skips); - setSelectedSnapshotIds((prev) => - pruneSelectedIds( - prev, - snaps.map((s) => s.id) - ) - ); - setSelectedWaveSkipIds((prev) => - pruneSelectedIds( - prev, - skips.map((s) => s.id) - ) - ); - setSelectedGcIds((prev) => - pruneSelectedIds( - prev, - snaps.filter(snapshotHasGoldenCombo).map((s) => s.id) - ) - ); + const updatedRuns = await api.listRuns(activeFilter); setRuns(updatedRuns); setSelected(updatedRuns.find((r) => r.id === selectedRunId) ?? null); } catch { /* keep last chart */ } - }, [selectedRunId, listFilter, hasOngoingSelectedRun]); + }, [selectedRunId, listFilter, hasOngoingSelectedRun, showRunRows]); const refreshSelectedRunGuarded = useCallback(() => { if (selectedRefreshInFlightRef.current) return; @@ -1445,7 +1400,6 @@ function History() { useEffect(() => { if (!selectedRunId || !hasOngoingSelectedRun) return; liveRefreshAtRef.current = 0; - refreshSelectedRunGuarded(); const id = window.setInterval(refreshSelectedRunGuarded, 15_000); return () => window.clearInterval(id); }, [selectedRunId, hasOngoingSelectedRun, refreshSelectedRunGuarded]); @@ -1611,18 +1565,11 @@ function History() { } }; - const usingLiveChart = - hasOngoingSelectedRun && liveChartSnapshots.length > 0; - const chartSnapshotsForDisplay = usingLiveChart - ? liveChartSnapshots - : snapshots; - const chartSkipsForDisplay = usingLiveChart ? liveChartWaveSkips : waveSkips; - const chartData = snapshotsToChartData(chartSnapshotsForDisplay, { - alreadySampled: usingLiveChart, - }); - const skipMarkers = usingLiveChart - ? buildChartWaveJumpMarkers(liveChartWaveSkips, liveChartNormalJumps) - : buildWaveJumpMarkers(chartSnapshotsForDisplay, chartSkipsForDisplay); + const chartData = useMemo(() => snapshotsToChartData(snapshots), [snapshots]); + const skipMarkers = useMemo( + () => buildWaveJumpMarkers(snapshots, waveSkips), + [snapshots, waveSkips] + ); const hasJumpsOnChart = skipMarkers.length > 0; const hasGcOnChart = chartData.some((d) => d.golden_combo_caret != null); @@ -1640,12 +1587,9 @@ function History() { const compareSkipMarkers = useMemo( () => (compareRunIdsKey ? compareRunIdsKey.split(",") : []).map((id) => - buildChartWaveJumpMarkers( - compareWaveSkips[id] ?? [], - compareNormalJumps[id] ?? [] - ) + buildWaveJumpMarkers(compareSnapshots[id] ?? [], compareWaveSkips[id] ?? []) ), - [compareRunIdsKey, compareWaveSkips, compareNormalJumps] + [compareRunIdsKey, compareSnapshots, compareWaveSkips] ); const hasCompareSkips = compareSkipMarkers.some((markers) => markers.length > 0); const hasCompareGc = useMemo( @@ -2632,7 +2576,7 @@ function History() { -
+
@@ -2672,17 +2616,14 @@ function History() { - {sortedSnapshots.map((s) => ( + {snapshotPage.pageRows.map((s) => ( { - if (el) snapshotRowRefs.current.set(s.wave, el); - else snapshotRowRefs.current.delete(s.wave); - }} + ref={snapshotPage.rowRef(s.id)} className={ selectedSnapshotIds.has(s.id) ? "snapshot-selected" : "" } - onClick={() => toggleSnapshotId(s.id, s.wave)} + onClick={() => toggleSnapshotId(s.id)} > @@ -2723,6 +2664,12 @@ function History() {
toggleSnapshotId(s.id, s.wave)} + onChange={() => toggleSnapshotId(s.id)} aria-label={`Select wave ${s.wave}`} />
+
{gcSnapshots.length > 0 && ( @@ -2754,7 +2701,7 @@ function History() { -
+
@@ -2800,15 +2747,12 @@ function History() { - {sortedGcSnapshots.map((s) => { + {gcPage.pageRows.map((s) => { const editing = editingGcId === s.id; return ( { - if (el) gcRowRefs.current.set(s.id, el); - else gcRowRefs.current.delete(s.id); - }} + ref={gcPage.rowRef(s.id)} className={ selectedGcIds.has(s.id) ? "snapshot-selected" : "" } @@ -2926,6 +2870,12 @@ function History() {
+
)} @@ -2958,7 +2908,7 @@ function History() { -
+
@@ -2998,13 +2948,10 @@ function History() { - {sortedWaveSkips.map((s) => ( + {waveSkipPage.pageRows.map((s) => ( { - if (el) waveSkipRowRefs.current.set(s.id, el); - else waveSkipRowRefs.current.delete(s.id); - }} + ref={waveSkipPage.rowRef(s.id)} className={ selectedWaveSkipIds.has(s.id) ? "snapshot-selected" @@ -3044,6 +2991,12 @@ function History() {
+
)} diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx index deaaead..9c2bc10 100644 --- a/src/components/SettingsPage.tsx +++ b/src/components/SettingsPage.tsx @@ -11,6 +11,7 @@ import { Settings, WindowInfo, } from "../api"; +import { DATA_RESTORED_EVENT } from "../runRows"; import AccountsSettings from "./AccountsSettings"; import ScannerLogViewer from "./ScannerLogViewer"; import AppUpdater from "./AppUpdater"; @@ -341,6 +342,7 @@ function SettingsPage({ } const result = await api.restoreBackup(); if (!result) return; + window.dispatchEvent(new Event(DATA_RESTORED_EVENT)); await load(); const when = result.backup_created_at ? ` from ${new Date(result.backup_created_at).toLocaleString()}` diff --git a/src/components/TablePager.tsx b/src/components/TablePager.tsx new file mode 100644 index 0000000..abff337 --- /dev/null +++ b/src/components/TablePager.tsx @@ -0,0 +1,39 @@ +import { TABLE_PAGE_SIZE } from "../tablePage"; + +export default function TablePager({ + page, + totalPages, + totalRows, + setPage, +}: { + page: number; + totalPages: number; + totalRows: number; + setPage: (page: number) => void; +}) { + if (totalPages <= 1) return null; + const first = (page - 1) * TABLE_PAGE_SIZE + 1; + const last = Math.min(page * TABLE_PAGE_SIZE, totalRows); + return ( +
+ + Showing {first}–{last} of {totalRows} + +
+ + + Page {page} of {totalPages} + + +
+
+ ); +} diff --git a/src/runRows.test.ts b/src/runRows.test.ts new file mode 100644 index 0000000..33d68e0 --- /dev/null +++ b/src/runRows.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from "vitest"; +import type { RunRowsCursor, RunRowsPage, SnapshotRow } from "./api"; +import { mergeRunRows, RunRowsReader } from "./runRows"; + +function snapshot(wave: number): SnapshotRow { + return { + id: `s${wave}`, + wave, + tier: null, + coin_per_minute: null, + golden_combo_chance: null, + golden_combo_caret: null, + golden_combo_multiplier: null, + recorded_at: "2026-01-01T00:00:00Z", + }; +} + +/** Stands in for the `run_rows` command, with each snapshot's wave as its rowid. Calls wait + * until released, so a test can decide the order they finish in. */ +function fakeDb(initialWaves: number[]) { + const waves = [...initialWaves]; + const pending: (() => void)[] = []; + const calls: RunRowsCursor[] = []; + const fetchRows = (_runId: string, after: RunRowsCursor) => { + calls.push(after); + // Reads the table when the call is made, as the backend would. + const rows = waves.filter((w) => w > after.snapshot_rowid); + const page: RunRowsPage = { + snapshots: rows.map(snapshot), + wave_skips: [], + cursor: { + snapshot_rowid: Math.max(after.snapshot_rowid, ...rows), + wave_skip_rowid: 0, + }, + }; + return new Promise((resolve) => { + pending.push(() => resolve(page)); + }); + }; + return { + fetchRows, + calls, + add: (wave: number) => waves.push(wave), + remove: (wave: number) => waves.splice(waves.indexOf(wave), 1), + release: async (index = 0) => { + pending.splice(index, 1)[0](); + await new Promise((r) => setTimeout(r)); + }, + }; +} + +function loaded(reader: RunRowsReader) { + return reader.rows.snapshots.map((s) => s.wave); +} + +describe("mergeRunRows", () => { + const wave = (r: { wave: number }) => r.wave; + + it("appends rows that come after the existing ones", () => { + expect(mergeRunRows([{ wave: 1 }, { wave: 2 }], [{ wave: 3 }], wave)).toEqual([ + { wave: 1 }, + { wave: 2 }, + { wave: 3 }, + ]); + }); + + it("slots in a row at a lower wave", () => { + expect(mergeRunRows([{ wave: 1 }, { wave: 5 }], [{ wave: 3 }], wave)).toEqual([ + { wave: 1 }, + { wave: 3 }, + { wave: 5 }, + ]); + }); + + it("keeps arrival order among equal waves", () => { + const merged = mergeRunRows( + [{ wave: 1, id: "old" }], + [{ wave: 1, id: "new" }], + wave + ); + expect(merged.map((r) => r.id)).toEqual(["old", "new"]); + }); +}); + +describe("RunRowsReader", () => { + it("only asks for rows past what it already has", async () => { + const db = fakeDb([1, 2]); + const reader = new RunRowsReader("run", db.fetchRows); + const load = reader.load(); + await db.release(); + await load; + + db.add(3); + const read = reader.readNew(); + await db.release(); + + expect((await read)?.snapshots.map((s) => s.wave)).toEqual([1, 2, 3]); + expect(db.calls[1].snapshot_rowid).toBe(2); + }); + + it("reports no change, and keeps the same arrays, when nothing was added", async () => { + const db = fakeDb([1]); + const reader = new RunRowsReader("run", db.fetchRows); + const load = reader.load(); + await db.release(); + await load; + const before = reader.rows; + + const read = reader.readNew(); + await db.release(); + + expect(await read).toBeNull(); + expect(reader.rows).toBe(before); + }); + + it("does a full load if none has landed, including after one failed", async () => { + let fail = true; + const db = fakeDb([1]); + const reader = new RunRowsReader("run", (id, after) => { + if (fail) { + fail = false; + return Promise.reject(new Error("db busy")); + } + return db.fetchRows(id, after); + }); + await expect(reader.load()).rejects.toThrow("db busy"); + + const read = reader.readNew(); + await db.release(); + + expect((await read)?.snapshots.map((s) => s.wave)).toEqual([1]); + }); + + it("doesn't start a read while a full load is running", async () => { + const db = fakeDb([1]); + const reader = new RunRowsReader("run", db.fetchRows); + const load = reader.load(); + + expect(await reader.readNew()).toBeNull(); + expect(db.calls).toHaveLength(1); + + await db.release(); + await load; + }); + + it("doesn't add a row twice when reads overlap", async () => { + const db = fakeDb([1]); + const reader = new RunRowsReader("run", db.fetchRows); + const load = reader.load(); + await db.release(); + await load; + + db.add(2); + const first = reader.readNew(); + expect(await reader.readNew()).toBeNull(); + await db.release(); + await first; + + expect(loaded(reader)).toEqual([1, 2]); + }); + + it("doesn't bring a deleted row back when an older read finishes late", async () => { + const db = fakeDb([1]); + const reader = new RunRowsReader("run", db.fetchRows); + const load = reader.load(); + await db.release(); + await load; + + db.add(2); + const staleRead = reader.readNew(); // Sees wave 2... + db.remove(2); // ...which is then deleted, so the edit triggers a full load. + const reload = reader.load(); + + await db.release(1); + await reload; + await db.release(0); + + expect(await staleRead).toBeNull(); + expect(loaded(reader)).toEqual([1]); + }); + + it("keeps only the newest of two overlapping full loads", async () => { + const db = fakeDb([1]); + const reader = new RunRowsReader("run", db.fetchRows); + const stale = reader.load(); + db.add(2); + const latest = reader.load(); + + await db.release(1); + await latest; + await db.release(0); + + expect(await stale).toBeNull(); + expect(loaded(reader)).toEqual([1, 2]); + }); +}); diff --git a/src/runRows.ts b/src/runRows.ts new file mode 100644 index 0000000..ba281d5 --- /dev/null +++ b/src/runRows.ts @@ -0,0 +1,96 @@ +import { + api, + START_OF_RUN_ROWS, + type RunRowsCursor, + type RunRowsPage, + type SnapshotRow, + type WaveSkipRow, +} from "./api"; + +export type RunRows = Pick; + +export const EMPTY_RUN_ROWS: RunRows = { snapshots: [], wave_skips: [] }; + +/** Rows of a run were edited or deleted: anything else showing that run must reload it. */ +export const RUN_ROWS_EDITED_EVENT = "wavetrace-run-rows-edited"; +/** A backup replaced the database, renumbering rows: every reader must reload. */ +export const DATA_RESTORED_EVENT = "wavetrace-data-restored"; + +/** `added` merged into `rows`, keeping the order of `key`. Equal keys stay in arrival + * order, and a stable sort of almost-sorted rows is cheap. */ +export function mergeRunRows(rows: T[], added: T[], key: (row: T) => number): T[] { + return [...rows, ...added].sort((a, b) => key(a) - key(b)); +} + +const snapshotWave = (s: SnapshotRow) => s.wave; +const skipWave = (s: WaveSkipRow) => s.at_wave; + +/** + * One run's rows, kept current by fetching only what's been added since the last read. The + * scanner only appends, so that's all a live view needs between full loads; fetching a long + * run's every row on each refresh made every refresh a stall. + * + * Both methods resolve to the rows to show, or null when there's nothing new to show: + * unchanged, or the result was superseded by a full load that started after it. + */ +export class RunRowsReader { + rows: RunRows = EMPTY_RUN_ROWS; + /** Null until a full load lands. */ + private cursor: RunRowsCursor | null = null; + /** Bumped by each full load, so an older fetch can't undo it: rows read before a delete + * must not bring the deleted row back. */ + private generation = 0; + private loading = false; + private reading = false; + + constructor( + readonly runId: string, + private readonly fetchRows: ( + runId: string, + after: RunRowsCursor + ) => Promise = api.runRows + ) {} + + /** Read the whole run, replacing what's held. */ + async load(): Promise { + const generation = ++this.generation; + this.cursor = null; + this.loading = true; + try { + const page = await this.fetchRows(this.runId, START_OF_RUN_ROWS); + if (generation !== this.generation) return null; + this.cursor = page.cursor; + this.rows = { snapshots: page.snapshots, wave_skips: page.wave_skips }; + return this.rows; + } finally { + if (generation === this.generation) this.loading = false; + } + } + + /** Read rows added since the last read. Falls back to a full load if none has landed. */ + async readNew(): Promise { + if (this.loading || this.reading) return null; + if (!this.cursor) return this.load(); + const generation = this.generation; + this.reading = true; + try { + const page = await this.fetchRows(this.runId, this.cursor); + if (generation !== this.generation) return null; + this.cursor = page.cursor; + if (page.snapshots.length === 0 && page.wave_skips.length === 0) return null; + this.rows = { + snapshots: + page.snapshots.length > 0 + ? mergeRunRows(this.rows.snapshots, page.snapshots, snapshotWave) + : this.rows.snapshots, + wave_skips: + page.wave_skips.length > 0 + ? mergeRunRows(this.rows.wave_skips, page.wave_skips, skipWave) + : this.rows.wave_skips, + }; + return this.rows; + } finally { + this.reading = false; + } + } +} diff --git a/src/tablePage.test.ts b/src/tablePage.test.ts new file mode 100644 index 0000000..afd4607 --- /dev/null +++ b/src/tablePage.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { pageCount, pageOfIndex } from "./tablePage"; + +describe("table paging", () => { + it("always has at least one page", () => { + expect(pageCount(0, 100)).toBe(1); + }); + + it("only starts a new page once a page is full", () => { + expect(pageCount(100, 100)).toBe(1); + expect(pageCount(101, 100)).toBe(2); + }); + + it("finds the page holding a row", () => { + expect(pageOfIndex(0, 100)).toBe(1); + expect(pageOfIndex(99, 100)).toBe(1); + expect(pageOfIndex(100, 100)).toBe(2); + }); +}); diff --git a/src/tablePage.ts b/src/tablePage.ts new file mode 100644 index 0000000..7fdff8d --- /dev/null +++ b/src/tablePage.ts @@ -0,0 +1,89 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +/** Rows rendered per page in History's run-detail tables. Their row count grows for as + * long as a run lasts, and a long run reached tens of thousands of DOM elements. */ +export const TABLE_PAGE_SIZE = 100; + +export function pageCount(rowCount: number, pageSize = TABLE_PAGE_SIZE): number { + return Math.max(1, Math.ceil(rowCount / pageSize)); +} + +/** 1-based page holding the row at `index`. */ +export function pageOfIndex(index: number, pageSize = TABLE_PAGE_SIZE): number { + return Math.floor(index / pageSize) + 1; +} + +/** + * One page of `rows`, plus `reveal(id)` to bring a row on any page into view (a chart click + * can select a row that isn't currently rendered). Returns to page 1 when `resetKey` changes. + */ +export function useTablePage(rows: T[], resetKey: unknown) { + const [page, setPage] = useState(1); + const [revealId, setRevealId] = useState(null); + const rowsRef = useRef(rows); + rowsRef.current = rows; + const wrapRef = useRef(null); + const rowEls = useRef(new Map()); + + const totalPages = pageCount(rows.length); + const safePage = Math.min(page, totalPages); + const start = (safePage - 1) * TABLE_PAGE_SIZE; + const pageRows = useMemo( + () => rows.slice(start, start + TABLE_PAGE_SIZE), + [rows, start] + ); + + useEffect(() => { + setPage(1); + }, [resetKey]); + + useEffect(() => { + wrapRef.current?.scrollTo({ top: 0 }); + }, [safePage]); + + // After the page-change effect above, and after commit so the row is mounted. + useEffect(() => { + if (revealId === null) return; + // Scroll the table's own box only: scrollIntoView also scrolls the page, which took + // the chart off screen on every point clicked in it. + const wrap = wrapRef.current; + const row = rowEls.current.get(revealId); + if (wrap && row) { + const w = wrap.getBoundingClientRect(); + const r = row.getBoundingClientRect(); + if (r.top < w.top || r.bottom > w.bottom) { + wrap.scrollBy({ + top: r.top - w.top - (w.height - r.height) / 2, + behavior: "smooth", + }); + } + } + setRevealId(null); + }, [revealId, safePage]); + + const reveal = useCallback((id: string) => { + const index = rowsRef.current.findIndex((r) => r.id === id); + if (index < 0) return; + setPage(pageOfIndex(index)); + setRevealId(id); + }, []); + + const rowRef = useCallback( + (id: string) => (el: HTMLTableRowElement | null) => { + if (el) rowEls.current.set(id, el); + else rowEls.current.delete(id); + }, + [] + ); + + return { + pageRows, + page: safePage, + totalPages, + totalRows: rows.length, + setPage, + wrapRef, + rowRef, + reveal, + }; +}