Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions DESIGN.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json",
"tauri": "tauri",
"test": "node --test scripts/filters.test.ts scripts/format.test.ts scripts/changelog.test.ts scripts/messages.test.ts scripts/i18n.test.ts scripts/outside.test.ts",
"test": "node --test scripts/filters.test.ts scripts/sidebar.test.ts scripts/format.test.ts scripts/changelog.test.ts scripts/messages.test.ts scripts/i18n.test.ts scripts/outside.test.ts",
"bump": "node scripts/bump.ts",
"format": "prettier --write .",
"format:check": "prettier --check ."
Expand Down
45 changes: 8 additions & 37 deletions scripts/filters.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
// node --test scripts/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
collectionFilter,
filterChips,
filterGroups,
isList,
matches,
removeChip,
storeSegments,
titleMatches,
toggleFilter,
type Filter,
} from '../src/lib/filters.ts'
import { collectionFilter, filterChips, filterGroups, matches, removeChip, storeSegments, titleMatches, toggleFilter, type Filter } from '../src/lib/filters.ts'

test('chips follow the popover order, one per filter that is on', () => {
assert.deepEqual(filterChips([]), [])
Expand Down Expand Up @@ -107,37 +96,19 @@ test('the new groups widen inside and narrow across', () => {
)
})

const collections = [
{ id: 3, name: 'Backlog', count: 2 },
{ id: 7, name: 'Co-op', count: 1 },
]

test('Lists come after Status: Favorites, each collection, then Hidden', () => {
const lists = filterGroups(collections)[1]
assert.deepEqual(lists, { label: 'Lists', filters: ['favorites', 'collection-3', 'collection-7', 'hidden'] })
assert.deepEqual(filterGroups([])[1].filters, ['favorites', 'hidden'])
assert.deepEqual(
filterGroups([]).map((g) => g.label),
['Status', 'Lists', 'Your playtime', 'How long to beat', 'Has'],
)
})

test('list chips are named after the list and come after Status', () => {
const on: Filter[] = ['bothStores', 'hidden', collectionFilter(7), 'notInstalled', 'favorites']
test('the popover has no Lists group', () => {
assert.deepEqual(
filterChips(on, collections).map((c) => c.label),
['Not installed', 'Favorites', 'Co-op', 'Hidden', 'On more than one store'],
filterGroups().map((g) => g.label),
['Status', 'Your playtime', 'How long to beat', 'Has'],
)
const left = removeChip(on, filterChips(on, collections)[2])
assert.deepEqual(left, ['bothStores', 'hidden', 'notInstalled', 'favorites'])
assert.ok(isList('collection-7') && isList('hidden') && !isList('update'))
})

test('lists widen each other and narrow the other groups', () => {
test('the view relies on lists widening each other and narrowing the other groups', () => {
const fav = { ...game, favorite: true }
const inCoop = { ...game, collections: [7] }
const hidden = { ...game, hidden: true, installed: false }
assert.ok(matches(fav, ['favorites'], {}))
assert.ok(!matches(game, ['favorites'], {}))
assert.ok(!matches(inCoop, ['favorites'], {}))
assert.ok(matches(inCoop, ['favorites', collectionFilter(7)], {}))
assert.ok(!matches(inCoop, [collectionFilter(3)], {}))
Expand All @@ -154,10 +125,10 @@ test('more than one store means two or more, of any stores', () => {
})

test('the Has group shows only with more than one store in use', () => {
const ids = (multi: boolean) => filterGroups([], multi).flatMap((g) => g.filters)
const ids = (multi: boolean) => filterGroups(multi).flatMap((g) => g.filters)
assert.ok(ids(true).includes('bothStores'))
assert.ok(!ids(false).includes('bothStores'))
assert.equal(filterGroups([], false).length, filterGroups([]).length - 1)
assert.equal(filterGroups(false).length, filterGroups().length - 1)
})

test('store segments: All plus the stores in use, none for a single store', () => {
Expand Down
46 changes: 46 additions & 0 deletions scripts/sidebar.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// node --test scripts/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { downloadFraction, fallbackView, viewCount, viewLists, withView } from '../src/lib/sidebar.ts'
import type { Filter } from '../src/lib/filters.ts'
import type { Progress, QueueView } from '../src/lib/bindings.ts'

const counts = { library: 9, favorites: 2, hidden: 1 }
const collections = [{ id: 3, name: 'Backlog', count: 4, covers: [] }]

test('the view joins the filters matches() gets', () => {
assert.deepEqual(withView(['notInstalled'], 'collection-3'), ['notInstalled', 'collection-3'])
const f: Filter[] = ['update']
assert.deepEqual(withView(f, null), f)
})

test('the library is asked for the view as its only list', () => {
assert.deepEqual(viewLists(null), [])
assert.deepEqual(viewLists('hidden'), ['hidden'])
})

test('a view counts its own games', () => {
assert.equal(viewCount(null, counts, collections), 9)
assert.equal(viewCount('favorites', counts, []), 2)
assert.equal(viewCount('hidden', counts, []), 1)
assert.equal(viewCount('collection-3', counts, collections), 4)
})

test('a view whose row is gone falls back to the library', () => {
assert.equal(fallbackView('favorites', { ...counts, favorites: 0 }, []), null)
assert.equal(fallbackView('favorites', counts, []), 'favorites')
assert.equal(fallbackView('hidden', { ...counts, hidden: 0 }, []), null)
assert.equal(fallbackView('collection-3', counts, []), null)
assert.equal(fallbackView('collection-3', counts, collections), 'collection-3')
assert.equal(fallbackView(null, counts, []), null)
})

const job = (fraction: number) => ({ fraction }) as Progress

test('the download fraction is the active job, else the average, else 0', () => {
const queue = (active: string | null) => ({ jobs: [], paused: false, active }) as QueueView
assert.equal(downloadFraction({ a: job(0.2), b: job(0.9) }, queue('b')), 0.9)
assert.ok(Math.abs(downloadFraction({ a: job(0.2), b: job(0.6) }, queue(null)) - 0.4) < 1e-9)
assert.equal(downloadFraction({}, queue(null)), 0)
assert.equal(downloadFraction({ a: job(0.5) }, queue('gone')), 0.5)
})
51 changes: 51 additions & 0 deletions src-tauri/src/commands/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,34 @@ pub struct Library {
amazon_attention: bool,
/// The stores the whole library has a game from, in toolbar order; games the owner added don't count.
stores: Vec<ProviderKind>,
/// For the sidebar's rows.
counts: Counts,
}

#[derive(Serialize, specta::Type)]
pub struct Counts {
/// Cards that are not hidden.
library: usize,
/// Favorites that are not hidden.
favorites: usize,
hidden: usize,
}

fn sidebar_counts(entries: &[Entry], games: &[Game], lists: &Lists) -> Counts {
let mut c = Counts {
library: 0,
favorites: 0,
hidden: 0,
};
for e in entries {
if lists.hidden(e, games) {
c.hidden += 1;
} else {
c.library += 1;
c.favorites += usize::from(lists.favorite(e, games));
}
}
c
}

/// `lists` are the Lists filters that are on ("favorites", "hidden", "collection-<id>"); the UI applies
Expand Down Expand Up @@ -171,6 +199,7 @@ pub fn library(
amazon: s.amazon_login,
amazon_attention,
stores: stores_in_use(&s.games),
counts: sidebar_counts(&s.entries, &s.games, &s.lists),
}
}

Expand Down Expand Up @@ -250,6 +279,8 @@ pub struct ViewPrefs {
pub async fn load_cache(app: AppHandle) -> Res<ViewPrefs> {
blocking(move || {
let state = app.state::<AppState>();
// Held until the lists are published, so a list change can't be overwritten by an older read.
let turn = state.lists_write.lock().expect("lists lock poisoned");
let conn = cache::db::open(&state.dirs.db)?;
let mut games = cache::db::load(&conn)?;
view::merge_last_played(&mut games, &cache::db::launches(&conn)?);
Expand All @@ -261,6 +292,7 @@ pub async fn load_cache(app: AppHandle) -> Res<ViewPrefs> {
let mut s = state.lock();
s.ttb = ttb;
s.lists = lists;
drop(turn);
// A scan that already finished wins over the cache.
if s.games.is_empty() {
s.games = games;
Expand Down Expand Up @@ -1863,6 +1895,24 @@ mod tests {
(games, entries, lists)
}

#[test]
fn sidebar_counts_count_cards_and_leave_hidden_out() {
use crate::view::tests::game;
let games = vec![
game("a", true, None, None),
game("b", true, None, None),
game("c", true, None, None),
];
let entries = entries::group(&games, &HashMap::new());
let lists = Lists {
favorite: HashSet::from([games[0].key(), games[1].key()]),
hidden: HashSet::from([games[1].key(), games[2].key()]),
..Lists::default()
};
let c = sidebar_counts(&entries, &games, &lists);
assert_eq!((c.library, c.favorites, c.hidden), (1, 1, 2));
}

#[test]
fn library_payload_snapshot() {
let (games, entries, lists) = payload_games();
Expand Down Expand Up @@ -1893,6 +1943,7 @@ mod tests {
amazon: None,
amazon_attention: false,
stores: stores_in_use(&games),
counts: sidebar_counts(&entries, &games, &lists),
};
insta::assert_json_snapshot!(library);
}
Expand Down
65 changes: 52 additions & 13 deletions src-tauri/src/commands/lists.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! Favorites, hidden games and collections. Stored per copy key, so setting one on a game sets every copy.

use std::collections::HashMap;

use serde::Serialize;
use tauri::{AppHandle, Manager};

Expand All @@ -14,8 +12,10 @@ use crate::msg::Msg;
pub struct Collection {
id: i64,
name: String,
/// Games in it.
/// Games in it, hidden ones left out.
count: usize,
/// Up to three entry keys of its games, most recently played first.
covers: Vec<String>,
}

/// Every copy key of the game with this key.
Expand All @@ -28,6 +28,8 @@ fn copy_keys(state: &AppState, key: &str) -> Res<Vec<String>> {
/// Runs a change on the database, then reads the lists again for the library.
fn change<T>(app: &AppHandle, f: impl FnOnce(&mut rusqlite::Connection) -> Res<T>) -> Res<T> {
let state = app.state::<AppState>();
// Held to the publish below, so two changes can't publish their reads out of order.
let _turn = state.lists_write.lock().expect("lists lock poisoned");
let mut conn = open_db(&state).ok_or(msg!(noDb))?;
let out = f(&mut conn)?;
let lists = cache::db::lists(&conn)?;
Expand Down Expand Up @@ -67,24 +69,39 @@ pub async fn collections(app: AppHandle) -> Res<Vec<Collection>> {
let state = app.state::<AppState>();
let list = collections_in(&open_db(&state).ok_or(msg!(noDb))?)?;
let s = state.lock();
let mut counts: HashMap<i64, usize> = HashMap::new();
for e in &s.entries {
for id in s.lists.collections(e, &s.games) {
*counts.entry(id).or_default() += 1;
}
}
Ok(list
.into_iter()
.map(|(id, name)| Collection {
id,
count: counts.get(&id).copied().unwrap_or(0),
name,
.map(|(id, name)| {
let (count, covers) = collection_summary(id, &s.entries, &s.games, &s.lists);
Collection {
id,
name,
count,
covers,
}
})
.collect())
})
.await
}

/// How many games a collection holds, hidden ones left out, and up to three of their keys, most recently
/// played first. `entries` are in title order, so the stable sort puts never-played ones after, by title.
fn collection_summary(
id: i64,
entries: &[entries::Entry],
games: &[crate::library::Game],
lists: &crate::view::Lists,
) -> (usize, Vec<String>) {
let mut members: Vec<&entries::Entry> = entries
.iter()
.filter(|e| !lists.hidden(e, games) && lists.collections(e, games).contains(&id))
.collect();
members.sort_by_key(|e| std::cmp::Reverse(entries::last_played(e, games).map(|p| p.0)));
let covers = members.iter().take(3).map(|e| e.key.clone()).collect();
(members.len(), covers)
}

/// The name to store: trimmed, not empty, and not another collection's in any case.
fn check_name(name: &str, taken: &[(i64, String)], except: Option<i64>) -> Res<String> {
let name = name.trim();
Expand Down Expand Up @@ -174,4 +191,26 @@ mod tests {
assert_eq!(check_name("BACKLOG", &taken, Some(1)).unwrap(), "BACKLOG");
assert!(check_name("co-op ", &taken, Some(1)).is_err());
}

#[test]
fn collection_summary_skips_hidden_and_takes_three_latest_covers() {
use crate::view::tests::game;
use std::collections::{HashMap, HashSet};
// Titles sort a..e; played 1..4 for a..d, e never, and "b" hidden.
let games: Vec<_> = [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 0)]
.into_iter()
.map(|(t, n)| game(t, true, None, (n > 0).then_some(n)))
.collect();
let entries = entries::group(&games, &HashMap::new());
let keys: Vec<String> = games.iter().map(|g| g.key()).collect();
let lists = crate::view::Lists {
hidden: HashSet::from([keys[1].clone()]),
collections: keys.iter().map(|k| (k.clone(), vec![7])).collect(),
..Default::default()
};
let (count, covers) = collection_summary(7, &entries, &games, &lists);
assert_eq!(count, 4);
assert_eq!(covers, [keys[3].clone(), keys[2].clone(), keys[0].clone()]);
assert_eq!(collection_summary(8, &entries, &games, &lists), (0, vec![]));
}
}
3 changes: 3 additions & 0 deletions src-tauri/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ pub struct AppState {
dirs: Dirs,
http: reqwest::Client,
shared: Mutex<Shared>,
/// Held from reading the lists in SQLite to publishing them in `shared`. Taken before `shared`, never after.
lists_write: Mutex<()>,
cover_jobs: tokio::sync::Semaphore,
/// Held across every Steam logon (download size, DLC, owned games), so they never stack.
steam_size: tokio::sync::Mutex<()>,
Expand Down Expand Up @@ -157,6 +159,7 @@ impl AppState {
status: vec![msg!(loadingLibrary)],
..Shared::default()
}),
lists_write: Mutex::new(()),
cover_jobs: tokio::sync::Semaphore::new(COVER_JOBS),
steam_size: tokio::sync::Mutex::new(()),
scans: library::ScanTurns::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,10 @@ expression: library
"steam",
"epic",
"gog"
]
],
"counts": {
"library": 2,
"favorites": 1,
"hidden": 0
}
}
Loading
Loading