Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

feat(library): filter local games by installation folder

domsvoboda36e5bc10b82b
diff --git a/assets/locales/de.json b/assets/locales/de.json
index b514bdf..3f916c7 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -105,5 +105,6 @@
"message.microsoft_content_licensing_returned_a_server_er_44d6063": "Die Microsoft Inhaltslizensierung meldet einen Server-Fehler (HTTP {{code}}). Versuche es später erneut.",
"message.microsoft_content_licensing_timed_out_check_your_af25eae": "Die Microsoft Inhaltslizensierung hat die Zeitbegrenzung ausgelöst. Prüfe deine Verbindung und versuche es erneut.",
"message.microsoft_could_not_be_reached_check_your_31b6c73": "Microsoft konnte nicht erreicht werden. Prüfe deine Verbindung und versuche es erneut.",
- "native.download_complete_2063789": "Download abgeschlossen"
+ "native.download_complete_2063789": "Download abgeschlossen",
+ "library.all_locations": "Alle Speicherorte"
}
diff --git a/assets/locales/en.json b/assets/locales/en.json
index e460203..0db19bd 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -1098,5 +1098,6 @@
"cloud.unavailable": "Cloud sync is unavailable for this session. Progress may only be saved on this device. Keep your local saves.",
"cloud.upload": "Cloud sync reported an error while finishing. The latest progress may not be available on other devices. Keep your local saves.",
"cloud.view_game": "View game",
- "cloud.conflict_retry": "Cloud sync is paused. Close the game, then start it again and choose a save in the conflict dialog. Keep your local saves until your choice succeeds."
+ "cloud.conflict_retry": "Cloud sync is paused. Close the game, then start it again and choose a save in the conflict dialog. Keep your local saves until your choice succeeds.",
+ "library.all_locations": "All locations"
}
diff --git a/assets/locales/es.json b/assets/locales/es.json
index e518350..c6f6011 100644
--- a/assets/locales/es.json
+++ b/assets/locales/es.json
@@ -1074,5 +1074,6 @@
"ui.your_owned_games_game_pass_games_and_local_insta_ebb2bf4": "Tus juegos en propiedad, los juegos de Game Pass y las instalaciones locales.",
"ui.your_pc_games_brought_together_354f2fc": "Tus juegos de PC, todos juntos.",
"ui.your_settings_and_games_will_not_change_3e99619": "Tu configuración y tus juegos no cambiarán.",
- "ui.your_wallet_provider_handles_its_password_window_eb886e1": "Tu proveedor de cartera gestiona su ventana de contraseña. Nexus no recibe la contraseña, no activa una cartera desactivada ni restablece las credenciales guardadas."
+ "ui.your_wallet_provider_handles_its_password_window_eb886e1": "Tu proveedor de cartera gestiona su ventana de contraseña. Nexus no recibe la contraseña, no activa una cartera desactivada ni restablece las credenciales guardadas.",
+ "library.all_locations": "Todas las ubicaciones"
}
diff --git a/assets/locales/fr.json b/assets/locales/fr.json
index f009fc1..69576e2 100644
--- a/assets/locales/fr.json
+++ b/assets/locales/fr.json
@@ -222,5 +222,6 @@
"message.the_download_server_is_rate_limiting_requests_ht_a9df1b2": "Le serveur de téléchargement n'accepte qu'un nombre limité de demandes (HTTP 429). Patientez avant de réessayer. Les fichiers partiels sont maintenus. Réessayez l'installation pour rafraichir le lien et reprendre le téléchargement.",
"message.the_download_server_returned_an_unexpected_http_bd720a0": "Le serveur de téléchargement a renvoyé une réponse HTTP inattendue{{code}}. Les fichiers partiels sont conservés. Utilisez Réessayer l’installation pour actualiser le lien du paquet et reprendre.",
"message.the_download_stopped_receiving_data_after_repeat_d1878f8": "Le téléchargement s'est interrompu malgré plusieurs tentatives. Les fichiers partiels sont maintenus. Réessayez l'installation pour rafraichir le lien et reprendre le téléchargement.",
- "message.the_game_could_not_be_launched_cadba92": "Le jeu a échoué à se lancer."
+ "message.the_game_could_not_be_launched_cadba92": "Le jeu a échoué à se lancer.",
+ "library.all_locations": "Tous les emplacements"
}
diff --git a/assets/locales/it.json b/assets/locales/it.json
index 7cc4f86..9fe61f1 100644
--- a/assets/locales/it.json
+++ b/assets/locales/it.json
@@ -114,5 +114,6 @@
"message.microsoft_package_metadata_was_unavailable_you_c_1e1a1b9": "I metadata del pacchetto Microsoft non sono disponibili. Puoi comunque utilizzare l'installazione manuale tramite Product ID.",
"message.microsoft_refused_the_offline_permission_request_eddf61e": "Microsoft ha negato la richiesta per il permesso offline.",
"message.microsoft_rejected_content_licensing_sign_in_htt_79214ca": "Microsoft ha rifiutato il login per le licenze dei contenuti (HTTP 401). Effettua nuovamente il login nelle Impostazioni.",
- "message.microsoft_rejected_the_request_sign_in_again_4e90559": "Microsoft ha rifiutato la richiesta. Effettua nuovamente il login nelle Impostazioni."
+ "message.microsoft_rejected_the_request_sign_in_again_4e90559": "Microsoft ha rifiutato la richiesta. Effettua nuovamente il login nelle Impostazioni.",
+ "library.all_locations": "Tutte le posizioni"
}
diff --git a/assets/locales/pl-PL.json b/assets/locales/pl-PL.json
index 6ca9cc8..76aa858 100644
--- a/assets/locales/pl-PL.json
+++ b/assets/locales/pl-PL.json
@@ -750,5 +750,6 @@
"downloads.update_backend_required": "Zaktualizuj backend Nexus w Ustawieniach, zanim bezpiecznie zaktualizujesz zainstalowane gry.",
"downloads.update_validation_failed": "Weryfikacja aktualizacji nie powiodła się. Wznów aktualizację przed rozpoczęciem gry.",
"friends.send_shortcut": "Enter, aby wysłać; Shift+Enter, aby dodać nową linię.",
- "game.back_to_store": "Powrót do Sklepu"
+ "game.back_to_store": "Powrót do Sklepu",
+ "library.all_locations": "Wszystkie lokalizacje"
}
diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json
index ada90fa..a0a0c05 100644
--- a/assets/locales/pt-BR.json
+++ b/assets/locales/pt-BR.json
@@ -1068,5 +1068,6 @@
"ui.your_pc_games_brought_together_354f2fc": "Seus jogos de PC, todos em um só lugar.",
"ui.your_settings_and_games_will_not_change_3e99619": "Suas configurações e jogos não serão alterados.",
"ui.your_wallet_provider_handles_its_password_window_eb886e1": "O provedor da sua carteira cuida da própria janela de senha. O Nexus não recebe a senha, não habilita uma carteira desabilitada nem redefine credenciais armazenadas.",
- "settings.cache_limit_error": "Insira um limite de cache entre 0,25 e 1024 GiB."
+ "settings.cache_limit_error": "Insira um limite de cache entre 0,25 e 1024 GiB.",
+ "library.all_locations": "Todos os locais"
}
diff --git a/assets/locales/zh-CN.json b/assets/locales/zh-CN.json
index 6fd7332..f80e2e8 100644
--- a/assets/locales/zh-CN.json
+++ b/assets/locales/zh-CN.json
@@ -745,5 +745,6 @@
"ui.your_pc_games_brought_together_354f2fc": "你的 PC 游戏,尽归一处。",
"ui.your_settings_and_games_will_not_change_3e99619": "你的设置和游戏不会改变。",
"ui.your_wallet_provider_handles_its_password_window_eb886e1": "钱包提供商自行处理其密码窗口。Nexus 不接收密码,也不启用已禁用的钱包或重置存储的凭据。",
- "settings.cache_limit_error": "请输入 0.25 至 1024 GiB 之间的缓存上限。"
+ "settings.cache_limit_error": "请输入 0.25 至 1024 GiB 之间的缓存上限。",
+ "library.all_locations": "所有位置"
}
diff --git a/assets/locales/zh-Hant.json b/assets/locales/zh-Hant.json
index 4683abf..97fa8a2 100644
--- a/assets/locales/zh-Hant.json
+++ b/assets/locales/zh-Hant.json
@@ -745,5 +745,6 @@
"ui.your_pc_games_brought_together_354f2fc": "你的 PC 遊戲,盡歸一處。",
"ui.your_settings_and_games_will_not_change_3e99619": "你的設定和遊戲不會改變。",
"ui.your_wallet_provider_handles_its_password_window_eb886e1": "錢包提供商自行處理其密碼視窗。Nexus 不接收密碼,也不啟用已停用的錢包或重置儲存的憑據。",
- "settings.cache_limit_error": "請輸入 0.25 至 1024 GiB 之間的快取上限。"
+ "settings.cache_limit_error": "請輸入 0.25 至 1024 GiB 之間的快取上限。",
+ "library.all_locations": "所有位置"
}
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 1e583b2..9b66240 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -20,7 +20,7 @@ import { defaultLaunchTools, normalizeLaunchTools } from '../shared/launch-tools
import { DEFAULT_SHADER_CACHE_GIB, shaderCacheLimits } from '../shared/shader-cache';
import type { GameLaunchTools } from '../shared/types';
import { catalogInstallRequest, PackageInstallProvider, usePackageInstall } from './PackageInstall';
-import { defaultLibraryFilters, loadLibraryFilters, saveLibraryFilters, libraryProductMatchesPlayState, rankLibraryRows, type LibraryFilters } from './library-preferences';
+import { defaultLibraryFilters, loadLibraryFilters, saveLibraryFilters, libraryProductMatchesPlayState, rankLibraryRows, libraryGameLocation, libraryLocations, type LibraryFilters } from './library-preferences';
import { InstallQueueShortcut } from './InstallQueueShortcut';
import { GamepadNavigation } from './GamepadNavigation';
import { requestTextKeyboard } from './touch-keyboard';
@@ -449,11 +449,12 @@ export function AccountGames({ data, toast, selectedId, select, menu, openProduc
const startPackageInstall = usePackageInstall();
const [localFilters, setLocalFilters] = useState<LibraryFilters>(defaultLibraryFilters);
const selectedFilters = filters ?? localFilters;
- const { kind, playState, query } = selectedFilters;
+ const { kind, playState, query, location } = selectedFilters;
+ const locations = libraryLocations(data.games, location);
const sort = kind === 'gamepass' ? selectedFilters.sort : undefined;
const updateFilters = (patch: Partial<LibraryFilters>) => (onFiltersChange ?? setLocalFilters)({ ...selectedFilters, ...patch });
const setKind = (kind: LibraryFilters['kind']) => updateFilters({ kind, sort:kind === 'gamepass' ? sort : undefined });
- const setPlayState = (playState: LibraryFilters['playState']) => updateFilters({ playState });
+ const setPlayState = (playState: LibraryFilters['playState']) => updateFilters({ playState, ...(playState === 'installable' ? {location:undefined} : {}) });
const setQuery = (query: string) => updateFilters({ query });
const [result, setResult] = useState<AccountLibraryPage>();
const [busy, setBusy] = useState(false);
@@ -496,7 +497,7 @@ export function AccountGames({ data, toast, selectedId, select, menu, openProduc
const visible = loadedIdentity === identity ? result : undefined;
// Installed games are already in the snapshot. Account searches must also
// resolve every remaining licensed page before reporting no matches.
- const searching = available && playState !== 'installed' && Boolean(query.trim()) && !error && (busy || Boolean(visible?.cursor));
+ const searching = available && !location && playState !== 'installed' && Boolean(query.trim()) && !error && (busy || Boolean(visible?.cursor));
useEffect(() => {
if (!searching || busy || !visible?.cursor || searchTerm !== query.trim()) return;
void load();
@@ -506,9 +507,9 @@ export function AccountGames({ data, toast, selectedId, select, menu, openProduc
const products = (visible?.products ?? []).filter(product => !installed.has(product.productId) && !installed.has(product.installProductId ?? ''));
const access = (game: Game) => game.storeId ? visible?.accessByProductId[game.storeId.toUpperCase()] : undefined;
const rows = rankLibraryRows([
- ...data.games.filter(game => playState !== 'installable' && (kind === 'all' || access(game) === kind)).sort((a, b) => a.title.localeCompare(b.title))
+ ...data.games.filter(game => (!location || libraryGameLocation(game) === location) && playState !== 'installable' && (kind === 'all' || access(game) === kind)).sort((a, b) => a.title.localeCompare(b.title))
.map(game => ({ id: game.id, title: game.title, game, product: undefined })),
- ...products.filter(product => libraryProductMatchesPlayState(product, playState)).map(product => ({ id: product.productId, title: product.title, product, game: undefined })),
+ ...products.filter(product => !location && libraryProductMatchesPlayState(product, playState)).map(product => ({ id: product.productId, title: product.title, product, game: undefined })),
].filter(row => row.title.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())),
sort ? visible?.recentProductIds : undefined, row => row.product?.productId ?? row.game?.storeId?.toUpperCase());
async function load(refresh = false) {
@@ -544,6 +545,7 @@ export function AccountGames({ data, toast, selectedId, select, menu, openProduc
<div className="library-filters" data-gamepad-filters>
<label>{ui("ui.access_ec5ba0a")}<select aria-label={ui("ui.access_ec5ba0a")} value={kind} onChange={event => setKind(event.target.value as AccountLibraryPage['kind'])}><option value="all">{ui("ui.all_games_cf2bf15")}</option><option value="owned">{ui("ui.owned_17b760c")}</option><option value="gamepass">{ui("ui.in_game_pass_69c8edf")}</option><option value="other">{ui("ui.other_access_542b2ae")}</option></select></label>
<label>{ui("ui.play_state_6f423d1")}<select aria-label={ui("ui.play_state_6f423d1")} value={playState} onChange={event => setPlayState(event.target.value as typeof playState)}><option value="all">{ui("ui.all_states_f189411")}</option><option value="installed">{ui("ui.installed_f8b32f4")}</option><option value="installable">{ui("ui.ready_to_install_bda18b9")}</option></select></label>
+ <label className="library-filter-location">{ui("ui.install_location_af47896")}<select aria-label={ui("ui.install_location_af47896")} title={location} value={location ?? ''} onChange={event => updateFilters({location:event.target.value || undefined, ...(event.target.value ? {playState:'installed'} : {})})}><option value="">{ui("library.all_locations")}</option>{locations.map(folder => <option key={folder} value={folder}>{folder}</option>)}</select></label>
{kind === 'gamepass' ? <label>{ui("ui.sort_bec6903")}<select aria-label={ui("ui.library_order_4dbb747")} value={sort ?? 'default'} onChange={event => updateFilters({sort:event.target.value === 'recent-gamepass' ? 'recent-gamepass' : undefined})}><option value="default">{ui("ui.default_order_f44484d")}</option><option value="recent-gamepass">{ui("ui.recently_added_to_game_pass_0c69d8c")}</option></select></label> : null}
<label className="library-filter-search">{ui("ui.search_49c266b")}<input aria-label={ui("ui.search_library_21a933a")} placeholder={ui("ui.search_your_games_17caf33")} value={query} onChange={event => setQuery(event.target.value)} /></label>
<button className="secondary library-refresh" aria-label={ui("ui.refresh_library_c628c56")} title={ui("ui.refresh_library_c628c56")} disabled={!available || busy} onClick={() => load(true)}>{busy ? <LoaderCircle className="spin" /> : <RefreshCw />}</button>
@@ -567,8 +569,8 @@ export function AccountGames({ data, toast, selectedId, select, menu, openProduc
const downloading = queued.has(product.productId) || queued.has(product.installProductId ?? '');
return <LibraryProductCard key={product.productId} product={product} present={present} downloading={downloading} installing={installing} canInstall={data.backend.capabilities.streaming} install={install} open={openProduct} />;
})}</div>
- {!busy && !searching && !error && !rows.length ? <p>{visible?.cursor && playState !== 'installed' ? ui("ui.no_games_match_these_filters_in_the_loaded_resul_10d7834") : ui("ui.no_games_match_these_filters_e0e0d54")}</p> : null}
- <div data-gamepad-library-footer><LibraryPagination loading={busy} hasMore={Boolean(visible?.cursor)} searching={searching} load={() => { void load(); }} />
+ {!busy && !searching && !error && !rows.length ? <p>{!location && visible?.cursor && playState !== 'installed' ? ui("ui.no_games_match_these_filters_in_the_loaded_resul_10d7834") : ui("ui.no_games_match_these_filters_e0e0d54")}</p> : null}
+ <div data-gamepad-library-footer><LibraryPagination loading={busy} hasMore={!location && Boolean(visible?.cursor)} searching={searching} load={() => { void load(); }} />
<p className="account-library-note">{ui("ui.licensed_games_are_listed_regardless_of_package_e204851")}</p></div>
{sort ? <p className="account-library-note">{ui("ui.microsoft_s_pc_game_pass_recently_added_collecti_75fb3d3")}</p> : null}
</div>
diff --git a/src/renderer/library-location.test.tsx b/src/renderer/library-location.test.tsx
new file mode 100644
index 0000000..6c21af8
--- /dev/null
+++ b/src/renderer/library-location.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+import {act, useState} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, expect, it, vi} from 'vitest';
+import {AccountGames} from './App';
+import {demoAccountLibrary, demoSnapshot} from '../shared/demo-data';
+import {installGamepadNavigation} from './gamepad-navigation';
+import {gamepadHarness} from './gamepad-test-harness';
+import {loadLibraryFilters, saveLibraryFilters} from './library-preferences';
+
+let root:Root;
+let data:ReturnType<typeof demoSnapshot>;
+const sd = '/run/media/deck/SD/Games';
+const location = () => document.querySelector<HTMLSelectElement>('select[aria-label="Install location"]')!;
+const state = () => document.querySelector<HTMLSelectElement>('select[aria-label="Play state"]')!;
+const cards = () => [...document.querySelectorAll<HTMLElement>('[data-gamepad-detail-target]')].map(card => card.dataset.gamepadDetailTarget);
+function Host() {
+ const [filters, setFilters] = useState(loadLibraryFilters);
+ return <AccountGames data={data} toast={()=>{}} filters={filters} onFiltersChange={next=>{setFilters(next);saveLibraryFilters(next);}}/>;
+}
+async function select(control:HTMLSelectElement, value:string) {
+ await act(async()=>{control.focus();control.value=value;control.dispatchEvent(new Event('change',{bubbles:true}));});
+}
+async function mount() {await act(async()=>{root.render(<Host/>);});}
+beforeEach(()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ vi.stubGlobal('localStorage',(globalThis as unknown as {jsdom:{window:Window}}).jsdom.window.localStorage);
+ localStorage.clear();
+ data=demoSnapshot();data.games=data.games.slice(0,3);
+ data.games[0].path=sd+'/Gears';data.games[1].path='/home/deck/Games/Forza';data.games[2].path=sd+'-other/Minecraft';
+ window.launcher={getAccountLibrary:vi.fn(async()=>demoAccountLibrary('all',new Map()))} as unknown as Window['launcher'];
+ document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);
+});
+afterEach(async()=>{await act(async()=>root.unmount());vi.restoreAllMocks();vi.unstubAllGlobals();document.body.innerHTML='';});
+
+it('filters exact folders, excludes uninstalled account games and retains native select focus',async()=>{
+ await mount();expect(cards()).toContain(data.games[1].id);
+ expect(cards()).toContain(demoAccountLibrary('all',new Map()).products[0].productId);
+ await select(location(),sd);
+ expect(cards()).toEqual([data.games[0].id]);
+ expect(state().value).toBe('installed');expect(document.activeElement).toBe(location());
+ expect(loadLibraryFilters().location).toBe(sd);
+ expect(window.launcher.getAccountLibrary).toHaveBeenCalledTimes(1);
+ expect([...location().options].map(option=>option.text)).toContain(sd);
+ expect([...location().options].map(option=>option.text)).not.toContain('Internal drive');
+ await select(state(),'installable');
+ expect(location().value).toBe('');expect(loadLibraryFilters().location).toBeUndefined();
+ expect(cards()).not.toContain(data.games[0].id);
+ expect(cards()).toContain(demoAccountLibrary('all',new Map()).products[0].productId);
+});
+
+it('restores a saved folder after recreating the library and keeps a now-empty folder selectable',async()=>{
+ await mount();await select(location(),sd);
+ await act(async()=>root.render(<div/>));await mount();
+ expect(location().value).toBe(sd);expect(cards()).toEqual([data.games[0].id]);
+ data={...data,games:data.games.slice(1)};await mount();
+ expect(location().value).toBe(sd);expect(cards()).toEqual([]);
+ expect(document.body.textContent).toContain('No games match these filters');
+ expect([...location().options].map(option=>option.value)).toContain(sd);
+ await select(location(),'');expect(cards()).toContain(data.games[1].id);
+});
+
+it('filters local games without sign-in or backend access, with no account requests',async()=>{
+ data.auth.stored=false;data.backend.available=false;data.backend.capabilities.library=false;
+ await mount();await select(location(),sd);
+ expect(cards()).toEqual([data.games[0].id]);expect(window.launcher.getAccountLibrary).not.toHaveBeenCalled();
+ expect(location().disabled).toBe(false);
+});
+
+it('selects a folder through the controller picker and returns focus after selecting or cancelling',async()=>{
+ await mount();const pad=gamepadHarness();
+ const stop=installGamepadNavigation(window,{mode:()=>{},back:()=>{},page:()=>{},social:()=>{},search:()=>{}});
+ const press=async(button:number)=>{await act(async()=>pad.press(button));};
+ try {
+ pad.step();location().focus();await press(2);await press(0);
+ const picker=document.querySelector<HTMLElement>('.gamepad-select-dialog')!;
+ expect(picker).not.toBeNull();
+ [...picker.querySelectorAll<HTMLElement>('button')].forEach((button,index)=>{button.dataset.testRect=`100,${100+index*50},250,44`;});
+ await press(13);await press(13);await press(0);
+ expect(location().value).toBe(sd);expect(cards()).toEqual([data.games[0].id]);
+ expect(document.activeElement).toBe(location());expect(document.querySelector('.gamepad-select-dialog')).toBeNull();
+ await press(0);expect(document.querySelector('.gamepad-select-dialog')).not.toBeNull();
+ await press(1);expect(document.querySelector('.gamepad-select-dialog')).toBeNull();
+ expect(location().value).toBe(sd);expect(document.activeElement).toBe(location());
+ } finally {stop();}
+});
diff --git a/src/renderer/library-preferences.test.ts b/src/renderer/library-preferences.test.ts
index 435cef1..d7e8414 100644
--- a/src/renderer/library-preferences.test.ts
+++ b/src/renderer/library-preferences.test.ts
@@ -51,3 +51,24 @@ it('puts ranked installed and available games together without mutating cards or
expect(rows.map(row=>row.id)).toEqual(['old-installed','new-available','old-available','new-installed']);
expect(rankLibraryRows(rows,undefined,row=>row.id)).toEqual(rows);
});
+
+it('persists an exact absolute library folder, rejects invalid values and clears it for Ready to install', () => {
+ let raw='';const storage={getItem:()=>raw,setItem:(_key:string,value:string)=>{raw=value;}};
+ const filters={...defaultLibraryFilters,playState:'installed' as const,location:'/run/media/deck/SD/Games/'};
+ expect(saveLibraryFilters(filters,storage)).toBe(true);
+ expect(loadLibraryFilters(storage)).toEqual({...filters,location:'/run/media/deck/SD/Games'});
+ for(const location of ['relative/Games',42,'/bad\0path','/bad\npath','/'+ 'x'.repeat(4096)]){
+ raw=JSON.stringify({...filters,location});expect(loadLibraryFilters(storage).location).toBeUndefined();
+ }
+ raw=JSON.stringify({...filters,playState:'installable'});expect(loadLibraryFilters(storage).location).toBeUndefined();
+});
+
+it('groups exact installation parent folders without inferring volume labels, and retains an empty saved folder', async () => {
+ const {libraryGameLocation,libraryLocations}=await import('./library-preferences');
+ const games=[{path:'/home/deck/Games/Forza'},{path:'/run/media/deck/SD/Games/Gears/'},{path:'/run/media/deck/SD/Games/Forza'},{path:'/run/media/deck/SD/Games-other/Test'},{path:'relative/Test'}];
+ expect(libraryGameLocation(games[1])).toBe('/run/media/deck/SD/Games');
+ expect(libraryGameLocation({path:'/Test'})).toBe('/');
+ expect(libraryGameLocation({path:'/'})).toBeUndefined();
+ expect(libraryLocations(games,'/mnt/unavailable/Games')).toEqual(['/home/deck/Games','/mnt/unavailable/Games','/run/media/deck/SD/Games','/run/media/deck/SD/Games-other']);
+ expect(games[1].path).toBe('/run/media/deck/SD/Games/Gears/');
+});
diff --git a/src/renderer/library-preferences.ts b/src/renderer/library-preferences.ts
index 874e025..c94981e 100644
--- a/src/renderer/library-preferences.ts
+++ b/src/renderer/library-preferences.ts
@@ -1,9 +1,10 @@
-import type { AccountLibraryPage, CatalogProduct } from '../shared/types';
+import type { AccountLibraryPage, CatalogProduct, Game } from '../shared/types';
export interface LibraryFilters {
kind: AccountLibraryPage['kind'];
playState: 'all' | 'installed' | 'installable';
query: string;
+ location?: string;
sort?: 'recent-gamepass';
}
export const defaultLibraryFilters: LibraryFilters = { kind: 'all', playState: 'all', query: '' };
@@ -19,6 +20,7 @@ function normalize(value: unknown): LibraryFilters {
return {
kind: record.kind === 'owned' || record.kind === 'gamepass' || record.kind === 'other' ? record.kind : 'all',
playState: record.playState === 'installed' || record.playState === 'installable' ? record.playState : 'all',
+ ...(record.playState !== 'installable' && validLocation(record.location) ? {location: validLocation(record.location)} : {}),
// Search is session-only, including when loading older saved preferences.
query: '',
...(record.kind === 'gamepass' && record.sort === 'recent-gamepass' ? {sort:'recent-gamepass' as const} : {}),
@@ -33,8 +35,8 @@ export function loadLibraryFilters(storage?: Preferences): LibraryFilters {
export function saveLibraryFilters(filters: LibraryFilters, storage?: Preferences): boolean {
try {
- const { kind, playState, sort } = normalize(filters);
- (storage ?? window.localStorage).setItem(key, JSON.stringify({ kind, playState, ...(sort ? {sort} : {}) }));
+ const { kind, playState, sort, location } = normalize(filters);
+ (storage ?? window.localStorage).setItem(key, JSON.stringify({ kind, playState, ...(sort ? {sort} : {}), ...(location ? {location} : {}) }));
return true;
}
catch { return false; }
@@ -46,3 +48,23 @@ export function rankLibraryRows<T>(rows: readonly T[], ids: readonly string[] |
const rank = new Map(ids.map((id,index) => [id,index]));
return [...rows].sort((a,b) => (rank.get(productId(a) ?? '') ?? ids.length) - (rank.get(productId(b) ?? '') ?? ids.length));
}
+
+function validLocation(value:unknown):string|undefined {
+ if (typeof value !== 'string' || !value.startsWith('/') || value.length > 4096 || /[\x00-\x1f\x7f]/.test(value)) return;
+ return value.replace(/\/+$/, '') || '/';
+}
+
+/** Group only by recorded installation folders, never infer a drive or volume type. */
+export function libraryGameLocation(game:Pick<Game, 'path'>):string|undefined {
+ const path = validLocation(game.path);
+ if (!path || path === '/') return;
+ return path.slice(0, path.lastIndexOf('/')) || '/';
+}
+
+export function libraryLocations(games:readonly Pick<Game, 'path'>[], selected?:string):string[] {
+ const locations = games.flatMap(game => libraryGameLocation(game) ?? []);
+ // A saved folder with no current games stays selectable and honestly empty.
+ const saved = validLocation(selected);
+ if (saved) locations.push(saved);
+ return [...new Set(locations)].sort((a,b) => a.localeCompare(b));
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 2ecb130..2df951d 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -256,6 +256,8 @@ button.primary svg, button.secondary svg { width: 17px; height: 17px; }
.library-filters select, .library-filters input { height: 36px; background: #292e35; color: #f1f3f5; border: 1px solid #4b515b; border-radius: 6px; padding: 7px 10px; }
.library-filters .library-refresh { flex: 0 0 36px; width: 36px; min-height: 36px; height: 36px; padding: 0; display: grid; place-items: center; }
.library-refresh svg { width: 17px; height: 17px; }
+.library-filter-location { min-width: 0; max-width: min(100%, 300px); }
+.library-filter-location select { width: 100%; text-overflow: ellipsis; }
.library-filter-search { flex: 1; min-width: 150px; }
.library-filter-search input { width: 100%; }
.library-license { display: block; margin: 8px 10px 0; color: #b8bec6; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }