refactor: moved queries to their own file

This commit is contained in:
Simeon Radivoev 2026-03-17 12:57:11 +02:00
parent 364bc9d0be
commit cf6fff6fac
Signed by: simeonradivoev
GPG key ID: 7611A451D2A5D37A
83 changed files with 1107 additions and 852 deletions

View file

@ -47,7 +47,7 @@
}, },
{ {
"type": "file", "type": "file",
"path": "../src/mainview/assets/256x256.png" "path": "../src/mainview/public/256x256.png"
}, },
{ {
"type": "script", "type": "script",

View file

@ -30,9 +30,11 @@
"cSpell.words": [ "cSpell.words": [
"elysia", "elysia",
"elysiajs", "elysiajs",
"emulatorjs",
"gameflow", "gameflow",
"hackolade", "hackolade",
"keytar", "keytar",
"mainview",
"norigin", "norigin",
"noriginmedia", "noriginmedia",
"romm" "romm"

View file

@ -11,7 +11,7 @@ import { rmdir } from "node:fs";
// ───────────────────────────────────────────── // ─────────────────────────────────────────────
const APP_DIR = process.env.BUILD_DIR ?? `./build/${process.platform}`; const APP_DIR = process.env.BUILD_DIR ?? `./build/${process.platform}`;
const BINARY_NAME = pkg.bin; const BINARY_NAME = pkg.bin;
const ICON = "./src/mainview/assets/256x256.png"; const ICON = "./src/mainview/public/256x256.png";
const DESKTOP = "./flatpak/com.simeonradivoev.gameflow-deck.desktop"; const DESKTOP = "./flatpak/com.simeonradivoev.gameflow-deck.desktop";
const TMP_FOLDER = "."; const TMP_FOLDER = ".";
// ───────────────────────────────────────────── // ─────────────────────────────────────────────

View file

@ -1,4 +1,4 @@
import Elysia, { sse, status } from "elysia"; import Elysia, { status } from "elysia";
import { config, events, jar, taskQueue } from "./app"; import { config, events, jar, taskQueue } from "./app";
import z from "zod"; import z from "zod";
import { client } from "@clients/romm/client.gen"; import { client } from "@clients/romm/client.gen";

View file

@ -7,7 +7,7 @@ import auth from "./auth";
export default new Elysia({ prefix: "/api/romm" }) export default new Elysia({ prefix: "/api/romm" })
.use([games, platforms, auth]) .use([games, platforms, auth])
.all("/*", async ({ request, params, set }) => .all("/*", async ({ request, set }) =>
{ {
set.headers["cross-origin-resource-policy"] = 'cross-origin'; set.headers["cross-origin-resource-policy"] = 'cross-origin';

View file

@ -401,7 +401,7 @@ export default new Elysia()
const res = await fetch(`https://cdn.emulatorjs.org/latest/data/cores/${params['*']}`); const res = await fetch(`https://cdn.emulatorjs.org/latest/data/cores/${params['*']}`);
return res; return res;
}) })
.get('/emulatorjs/data/*', async ({ params }) => .get('/emulatorjs/data/*', async () =>
{ {
return status("Not Found"); return status("Not Found");
}); });

View file

@ -181,7 +181,7 @@ export async function getValidLaunchCommands (data: {
'%FILENAME%': $.escape(path.basename(validFiles[0])) '%FILENAME%': $.escape(path.basename(validFiles[0]))
}; };
cmd = cmd.replace(/\%INJECT\%=(?<inject>[\w\%.\/\\]+)/g, (subscring, injectFile: string) => cmd = cmd.replace(/\%INJECT\%=(?<inject>[\w\%.\/\\]+)/g, (_, injectFile: string) =>
{ {
try try
{ {

View file

@ -230,7 +230,7 @@ export default async function buildStatusResponse (source: string, id: string)
dispose.forEach(f => f()); dispose.forEach(f => f());
}; };
}, },
cancel (reason) cancel ()
{ {
cleanup?.(); cleanup?.();
cleanup = undefined; cleanup = undefined;

View file

@ -1,7 +1,7 @@
import getFolderSize from "get-folder-size"; import getFolderSize from "get-folder-size";
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { config, db, emulatorsDb } from "../../app"; import { config, emulatorsDb } from "../../app";
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import * as schema from "@schema/app"; import * as schema from "@schema/app";
import { FrontEndGameType, FrontEndGameTypeDetailed, StoreGameType } from "@shared/constants"; import { FrontEndGameType, FrontEndGameTypeDetailed, StoreGameType } from "@shared/constants";
@ -103,15 +103,6 @@ export function convertLocalToFrontendDetailed (g: typeof schema.games.$inferSel
export async function convertStoreToFrontend (system: string, id: string, storeGame: StoreGameType): Promise<FrontEndGameType> export async function convertStoreToFrontend (system: string, id: string, storeGame: StoreGameType): Promise<FrontEndGameType>
{ {
let size: number | null = null;
try
{
const fileResponse = await fetch(storeGame.file, { method: 'HEAD' });
size = Number(fileResponse.headers.get('content-length'));
} catch (error)
{
console.error(error);
}
const rommSystem = await emulatorsDb.query.systemMappings.findFirst({ const rommSystem = await emulatorsDb.query.systemMappings.findFirst({
where: and(eq(emulatorSchema.systemMappings.system, system), eq(emulatorSchema.systemMappings.source, 'romm')) where: and(eq(emulatorSchema.systemMappings.system, system), eq(emulatorSchema.systemMappings.source, 'romm'))
}); });

View file

@ -165,7 +165,7 @@ export class InstallJob implements IJob
let bytesReceived = 0; let bytesReceived = 0;
const progressStream = new Transform({ const progressStream = new Transform({
transform (chunk, encoding, callback) transform (chunk, _, callback)
{ {
bytesReceived += chunk.length; bytesReceived += chunk.length;
if (totalBytes > 0) if (totalBytes > 0)

View file

@ -5,7 +5,7 @@ import { LoginJob } from "./login-job";
import TwitchLoginJob from "./twitch-login-job"; import TwitchLoginJob from "./twitch-login-job";
import UpdateStoreJob from "./update-store"; import UpdateStoreJob from "./update-store";
function registerJob<const Path extends string, TS, T extends { id: Path, dataSchema?: TS; }> (job: T, path: Path, dataSchema: TS) function registerJob<const Path extends string, TS, T extends { id: Path, dataSchema?: TS; }> (_job: T, path: Path, dataSchema: TS)
{ {
return new Elysia().ws(path, { return new Elysia().ws(path, {
body: z.discriminatedUnion('type', [ body: z.discriminatedUnion('type', [
@ -64,7 +64,7 @@ function registerJob<const Path extends string, TS, T extends { id: Path, dataSc
{ {
(ws.data as any).cleanup.forEach((d: Function) => d()); (ws.data as any).cleanup.forEach((d: Function) => d());
}, },
message (ws, message) message (_, message)
{ {
if (message.type === 'cancel') if (message.type === 'cancel')
{ {

View file

@ -1,11 +1,12 @@
import * as appSchema from '@schema/app'; import * as appSchema from '@schema/app';
import { findExec, findExecByName } from "../games/services/launchGameService"; import { findExecByName } from "../games/services/launchGameService";
import * as emulatorSchema from "@schema/emulators"; import * as emulatorSchema from "@schema/emulators";
import { eq, inArray } from 'drizzle-orm'; import { eq, inArray } from 'drizzle-orm';
import { customEmulators, db, emulatorsDb } from '../app'; import { customEmulators, db, emulatorsDb } from '../app';
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import { cores } from '../emulatorjs/emulatorjs'; import { cores } from '../emulatorjs/emulatorjs';
import { FrontEndEmulator } from '@/shared/constants';
/** /**
* Get emulators based on local games. Only the ones we probably need. * Get emulators based on local games. Only the ones we probably need.
@ -77,117 +78,40 @@ export async function getRelevantEmulators ()
systems.forEach(s => platformViability.set(s, true)); systems.forEach(s => platformViability.set(s, true));
} }
return { const em: FrontEndEmulator & { isCritical: boolean; path?: { path: string, type: string; }; } = {
emulator: emulator, name: emulator,
path: execPath,
exists: exists, exists: exists,
logo: platform ? `/api/romm/platform/local/${platform}/cover` : '',
systems: systems.map(s => platformLookup.get(s)).filter(s => !!s).map(e => ({ icon: `/api/romm/image/romm/assets/platforms/${e.es_slug}.svg`, name: e.platform_name ?? 'Unknown', id: e.es_slug ?? '' })),
gameCount: 0,
description: '',
homepage: '',
type: 'emulator',
os: [process.platform as any],
isCritical: false, isCritical: false,
path_cover: platform ? `/api/romm/platform/local/${platform}/cover` : null, path: execPath,
systems: systems.map(s => platformLookup.get(s)).filter(s => !!s)
}; };
return em;
})); }));
finalEmulators.push({ finalEmulators.push({
emulator: 'emulatorjs', name: 'emulatorjs',
exists: true, exists: true,
path: { path: 'localhost', type: 'js' }, path: { path: 'localhost', type: 'js' },
path_cover: `/api/romm/image?url=${encodeURIComponent('https://emulatorjs.org/logo/EmulatorJS.png')}`, logo: `/api/romm/image?url=${encodeURIComponent('https://emulatorjs.org/logo/EmulatorJS.png')}`,
isCritical: false, systems: [],
systems: [] gameCount: 0,
type: 'emulator',
description: '',
homepage: '',
os: [process.platform as any],
isCritical: false
}); });
return finalEmulators.map(e => return finalEmulators.map(e =>
{ {
e.isCritical = !e.systems.filter(s => s?.es_slug).some(s => !!platformViability.get(s?.es_slug!)); e.isCritical = !e.systems.filter(s => s?.id).some(s => !!platformViability.get(s?.id!));
return e; return e;
}); });
} }
/**
* Only emulators we strictly need based on local games. Emulator JS is included as bundled.
* If there is even single emulator for a system don't include emulators for that system.
*/
/*export async function getMissingEmulators ()
{
const localGames = await db.query.games.findMany({
columns: {
platform_id: true,
slug: true
},
with: {
platform: {
columns: {
name: true,
es_slug: true
}
},
}
});
const platformLookup = new Map(localGames.map(g => [g.platform.es_slug, g]));
const platformViability = new Map(localGames.map(g => [g.platform.es_slug, false]));
// all commands based on the local games
const commands = await emulatorsDb.query.commands.findMany({
columns: { command: true },
where: inArray(emulatorSchema.commands.system, Array.from(new Set(localGames.filter(g => g.platform.es_slug).map(s => s.platform.es_slug!)))),
with: { system: { columns: { name: true } } }
});
// get all emulators in said commands
const emulators = commands
.flatMap(command =>
{
const matches = command.command.match(/(?<=%EMULATOR_)[\w-]+(?=%)/);
if (!matches)
{
return undefined;
}
return matches?.map(m => ({ emulator: m, system: command.system?.name }));
}
).filter(c => !!c);
const groupedEmulators = Map.groupBy(emulators, ({ emulator }) => emulator);
const finalEmulators = await Promise.all(Array.from(groupedEmulators.entries()).map(async ([emulator, system_slug]) =>
{
let execPath: { path: string; type: string, } | undefined;
if (customEmulators.has(emulator))
{
execPath = { path: customEmulators.get(emulator), type: 'custom' };
} else
{
execPath = await findExecByName(emulator);
}
let platform: number | null | undefined = null;
if (system_slug.length <= 1)
{
platform = platformLookup.get(system_slug[0].system)?.platform_id;
}
// check if automatic or custom path found existing binary.
// This might not be the actual emulator but I don't care.
const exists = !!execPath && await fs.exists(execPath.path);
const systems = Array.from(new Set(system_slug.map(s => s.system)));
if (exists)
{
systems.forEach(s => platformViability.set(s, true));
}
return {
emulator: emulator,
path: execPath,
exists: exists,
isCritical: false,
path_cover: platform ? `/api/romm/platform/local/${platform}/cover` : null,
systems: systems.map(s => platformLookup.get(s)).filter(s => !!s)
};
}));
return finalEmulators.map(e =>
{
e.isCritical = !e.systems.filter(s => s?.es_slug).some(s => !!platformViability.get(s?.es_slug!));
return e;
});
}*/

View file

@ -194,7 +194,8 @@ export const store = new Elysia({ prefix: '/api/store' })
source: execPath?.type, source: execPath?.type,
location: execPath?.path location: execPath?.path
}, },
screenshots: screenshots.map(s => `/api/store/screenshot/emulator/${id}/${s}`) screenshots: screenshots.map(s => `/api/store/screenshot/emulator/${id}/${s}`),
gameCount: 0
}; };
return emulator; return emulator;

View file

@ -1,9 +1,7 @@
import { SERVER_PORT } from "@shared/constants"; import { SERVER_PORT } from "@shared/constants";
import path from 'node:path';
import appInfo from '~/package.json';
import { host } from "./utils/host"; import { host } from "./utils/host";
import { appPath } from "./utils"; import { appPath } from "./utils";
import Elysia, { file } from "elysia"; import Elysia from "elysia";
import cors from "@elysiajs/cors"; import cors from "@elysiajs/cors";
import staticPlugin from "@elysiajs/static"; import staticPlugin from "@elysiajs/static";
@ -17,11 +15,11 @@ export function RunBunServer ()
'cross-origin-opener-policy': 'same-origin', 'cross-origin-opener-policy': 'same-origin',
'cross-origin-resource-policy': 'cross-origin' 'cross-origin-resource-policy': 'cross-origin'
}) })
.get("/", ({ set }) => .get("/", () =>
{ {
return Bun.file(appPath("./dist/index.html")); return Bun.file(appPath("./dist/index.html"));
}) })
.get('/emulatorjs', ({ set }) => .get('/emulatorjs', () =>
{ {
return Bun.file(appPath('./dist/emulatorjs/index.html')); return Bun.file(appPath('./dist/emulatorjs/index.html'));
}) })

View file

@ -41,7 +41,6 @@ export async function BuildParams (data: BrowserParams)
args.push(`--app=${SERVER_URL(host)}`); args.push(`--app=${SERVER_URL(host)}`);
args.push(`--app-id=gameflow`); args.push(`--app-id=gameflow`);
args.push(`--force-app-mode`);
args.push('--no-default-browser-check'); args.push('--no-default-browser-check');
args.push('--new-instance'); args.push('--new-instance');
args.push('--no-first-run'); args.push('--no-first-run');

View file

@ -27,11 +27,6 @@ interface SpawnBrowserOptions
ipc?: (message: string) => void; ipc?: (message: string) => void;
} }
interface SpawnLastInfo
{
PID: number;
}
/** /**
* Spawns a browser process with proper handling for different installation types. * Spawns a browser process with proper handling for different installation types.
* *

View file

@ -1,9 +1,9 @@
import classNames from 'classnames';
import { CSSProperties, JSX, Ref, useEffect, useRef, useState } from 'react'; import { CSSProperties, JSX, Ref, useEffect, useRef, useState } from 'react';
import { twMerge } from 'tailwind-merge'; import { twMerge } from 'tailwind-merge';
import { useSessionStorage } from 'usehooks-ts'; import { useSessionStorage } from 'usehooks-ts';
import { mobileCheck, useLocalSetting } from '../scripts/utils'; import { useLocalSetting } from '../scripts/utils';
import { AnimatedBackgroundContext } from '../scripts/contexts'; import { AnimatedBackgroundContext } from '../scripts/contexts';
export function AnimatedBackground (data: { export function AnimatedBackground (data: {
@ -88,8 +88,6 @@ export function AnimatedBackground (data: {
}, [finalBackgroundUrl]); }, [finalBackgroundUrl]);
const isMobile = mobileCheck();
function handleSetBackground (url: string) function handleSetBackground (url: string)
{ {

View file

@ -39,11 +39,11 @@ export default function CardElement (data: GameCardParams & InteractParams)
{ {
const { ref, focused, focusSelf } = useFocusable({ const { ref, focused, focusSelf } = useFocusable({
focusKey: data.focusKey, focusKey: data.focusKey,
onFocus: (l, p, detals) => data.onFocus?.(data.id, ref.current as any, detals), onFocus: (l, p, details) => data.onFocus?.(data.id, ref.current as any, details),
onEnterPress: () => data.onAction?.(), onEnterPress: () => data.onAction?.(),
onBlur: () => data.onBlur?.(data.id) onBlur: () => data.onBlur?.(data.id)
}); });
const { isMouse, isPointer } = useActiveControl(); const { isPointer } = useActiveControl();
return ( return (
<li <li

View file

@ -24,6 +24,8 @@ export function CardList (data: {
onSelectGame?: (id: string) => void; onSelectGame?: (id: string) => void;
onGameFocus?: GameCardFocusHandler; onGameFocus?: GameCardFocusHandler;
className?: string; className?: string;
finalElement?: JSX.Element;
saveChildFocus?: 'session' | 'local';
}) })
{ {
const { ref, focusKey } = useFocusable({ const { ref, focusKey } = useFocusable({
@ -72,7 +74,7 @@ export function CardList (data: {
title="Games" title="Games"
id={`card-list-${data.id}`} id={`card-list-${data.id}`}
ref={ref} ref={ref}
save-child-focus="session" save-child-focus={data.saveChildFocus}
className={twMerge("items-center justify-center-safe h-full", className={twMerge("items-center justify-center-safe h-full",
data.grid ? "grid h-fit sm:gap-2 md:gap-5 auto-rows-min grid-cols-[repeat(auto-fill,var(--game-card-width))]" : data.grid ? "grid h-fit sm:gap-2 md:gap-5 auto-rows-min grid-cols-[repeat(auto-fill,var(--game-card-width))]" :
'landscape:grid landscape:grid-flow-col landscape:auto-cols-min auto-rows-[1fr] sm:gap-2 md:gap-4 portrait:grid portrait:auto-rows-min portrait:grid-cols-[repeat(auto-fill,var(--game-card-width))] *:portrait:aspect-8/10 *:landscape:aspect-8/12 sm:landscape:max-h-84 md:max-h-128!', 'landscape:grid landscape:grid-flow-col landscape:auto-cols-min auto-rows-[1fr] sm:gap-2 md:gap-4 portrait:grid portrait:auto-rows-min portrait:grid-cols-[repeat(auto-fill,var(--game-card-width))] *:portrait:aspect-8/10 *:landscape:aspect-8/12 sm:landscape:max-h-84 md:max-h-128!',
@ -83,10 +85,10 @@ export function CardList (data: {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
}} }}
style={{ scrollbarWidth: "none" }}
> >
<FocusContext.Provider value={focusKey}> <FocusContext.Provider value={focusKey}>
{data.games.map(BuildCard)} {data.games.map(BuildCard)}
{data.finalElement}
</FocusContext.Provider> </FocusContext.Provider>
</ul> </ul>
); );

View file

@ -0,0 +1,72 @@
import { twMerge } from "tailwind-merge";
import { RoundButton } from "./RoundButton";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { CSSProperties, Ref, useEffect, useRef, useState } from "react";
import useActiveControl from "../scripts/gamepads";
export default function Carousel (data: {
className?: string;
rootClassName?: string;
controlsClassName?: string;
children?: any;
scrollRef?: Ref<HTMLDivElement>;
scrollHandler?: (direction: number, element: HTMLDivElement) => void;
isScrollable?: boolean;
style?: CSSProperties;
})
{
const [scrollable, setScrollable] = useState(false);
const localRef = useRef<HTMLDivElement>(null);
const handleScroll = (dir: number) =>
{
if (!localRef.current) return;
if (data.scrollHandler)
{
data.scrollHandler(dir, localRef.current);
return;
}
localRef.current.scrollBy({ behavior: 'smooth', left: localRef.current.clientWidth / 2 * dir });
};
const { isMouse } = useActiveControl();
useEffect(() =>
{
const el = localRef.current;
if (!el) return;
setScrollable(el.scrollWidth > el.clientWidth);
const observer = new ResizeObserver(() =>
{
setScrollable(el.scrollWidth > el.clientWidth);
});
observer.observe(el);
return () => observer.disconnect();
}, [localRef.current, localRef.current?.clientWidth, localRef.current?.scrollWidth]);
return <div className={twMerge("relative scroll-smooth", data.rootClassName)}>
<div style={{ ...data.style, scrollSnapType: 'x mandatory' }} ref={r =>
{
if (data.scrollRef instanceof Function)
{
data.scrollRef(r);
} else if (data.scrollRef)
{
data.scrollRef.current = r;
}
localRef.current = r;
}} className={twMerge(data.className)}>
{data.children}
</div>
{((scrollable || data.isScrollable) && isMouse) && <>
<div className={twMerge("absolute flex items-center left-2 top-0 bottom-0", data.controlsClassName)}>
<RoundButton onAction={() => handleScroll(-1)} id="move-left" className="p-2 border-base-content/40"><ChevronLeft /></RoundButton>
</div>
<div className={twMerge("absolute flex items-center justify-end right-2 top-0 bottom-0", data.controlsClassName)}>
<RoundButton onAction={() => handleScroll(1)} id="move-left" className="p-2 border-base-content/40"><ChevronRight /></RoundButton>
</div>
</>}
</div>;
}

View file

@ -1,11 +1,11 @@
import { getCollectionsApiCollectionsGetOptions } from "@/clients/romm/@tanstack/react-query.gen"; import { RPC_URL } from "@/shared/constants";
import { DefaultRommStaleTime, RPC_URL } from "@/shared/constants";
import { useSuspenseQuery } from "@tanstack/react-query"; import { useSuspenseQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { CardList, GameMetaExtra } from "./CardList"; import { CardList, GameMetaExtra } from "./CardList";
import { SaveSource } from "../scripts/spatialNavigation"; import { SaveSource } from "../scripts/spatialNavigation";
import { GameCardFocusHandler } from "./CardElement"; import { GameCardFocusHandler } from "./CardElement";
import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation"; import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import queries from "../scripts/queries";
export default function CollectionList (data: { export default function CollectionList (data: {
id: string, id: string,
@ -13,14 +13,11 @@ export default function CollectionList (data: {
className?: string; className?: string;
onFocus?: GameCardFocusHandler; onFocus?: GameCardFocusHandler;
onSelect?: (id: string) => void; onSelect?: (id: string) => void;
saveChildFocus?: 'session' | 'local';
}) })
{ {
const navigate = useNavigate(); const navigate = useNavigate();
const { data: collections } = useSuspenseQuery({ const { data: collections } = useSuspenseQuery(queries.romm.getCollectionsQuery());
...getCollectionsApiCollectionsGetOptions(),
refetchOnWindowFocus: false,
staleTime: DefaultRommStaleTime
});
const handleDefaultSelect = (id: string) => const handleDefaultSelect = (id: string) =>
{ {
@ -33,6 +30,7 @@ export default function CollectionList (data: {
type="collection" type="collection"
id={data.id} id={data.id}
className={data.className} className={data.className}
saveChildFocus={data.saveChildFocus}
games={collections.sort((a, b) => Date.parse(a.updated_at) - Date.parse(b.updated_at)) games={collections.sort((a, b) => Date.parse(a.updated_at) - Date.parse(b.updated_at))
.map((g) => ({ .map((g) => ({
id: String(g.id), id: String(g.id),

View file

@ -1,25 +1,25 @@
import { AnimatedBackground } from './AnimatedBackground'; import { AnimatedBackground } from './AnimatedBackground';
import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation'; import { FocusContext, setFocus, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { HeaderUI } from './Header'; import { HeaderUI } from './Header';
import { GameList } from './GameList'; import { GameList } from './GameList';
import { Search, Settings2 } from 'lucide-react'; import { Search, Settings2 } from 'lucide-react';
import { JSX, Suspense } from 'react'; import { JSX, Suspense, useEffect } from 'react';
import Shortcuts from './Shortcuts'; import Shortcuts from './Shortcuts';
import { AutoFocus } from './AutoFocus'; import { AutoFocus } from './AutoFocus';
import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts'; import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts';
import { Router } from '..'; import { PopNavigateSource } from '../scripts/spatialNavigation';
import { PopNavigateSource, PopSource } from '../scripts/spatialNavigation';
import { GameListFilterType } from '@/shared/constants'; import { GameListFilterType } from '@/shared/constants';
import { GameCardFocusHandler } from './CardElement'; import { GameCardFocusHandler } from './CardElement';
export interface CollectionsDetailParams export interface CollectionsDetailParams
{ {
id?: string; id?: string;
setBackground: (url: string) => void; setBackground?: (url: string) => void;
filters?: GameListFilterType; filters?: GameListFilterType;
headerTitle?: JSX.Element; headerTitle?: JSX.Element;
title?: JSX.Element; title?: JSX.Element;
footer?: JSX.Element; footer?: JSX.Element;
focus?: string;
} }
export function CollectionsDetail (data: CollectionsDetailParams) export function CollectionsDetail (data: CollectionsDetailParams)
@ -37,10 +37,21 @@ export function CollectionsDetail (data: CollectionsDetailParams)
{ {
if (!(details.nativeEvent instanceof MouseEvent)) if (!(details.nativeEvent instanceof MouseEvent))
{ {
node.scrollIntoView({ block: 'center', behavior: 'smooth' }); node.scrollIntoView({ block: 'center', behavior: details.instant ? 'instant' : 'smooth' });
} }
}; };
useEffect(() =>
{
if (data.focus)
setFocus(data.focus, { instant: true });
}, [data.focus]);
useEffect(() =>
{
return () => setFocus('');
}, []);
return ( return (
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<AnimatedBackground animated ref={ref} backgroundKey="home-background" className='flex'> <AnimatedBackground animated ref={ref} backgroundKey="home-background" className='flex'>
@ -53,7 +64,6 @@ export function CollectionsDetail (data: CollectionsDetailParams)
<Suspense> <Suspense>
<GameList <GameList
grid grid
setBackground={data.setBackground}
filters={data.filters} filters={data.filters}
onFocus={handleScroll} onFocus={handleScroll}
id={`${focusKey}-list`}> id={`${focusKey}-list`}>

View file

@ -24,7 +24,7 @@ export function OptionElement (data: DialogEntry & { onFocus?: () => void; class
data.onFocus?.(); data.onFocus?.();
}; };
const handleAction = data.action ? () => data.action?.({ close: context.close, focus: focusSelf }) : undefined; const handleAction = data.action ? () => data.action?.({ close: context.close, focus: focusSelf }) : undefined;
const { ref, focused, focusSelf, focusKey, hasFocusedChild } = useFocusable({ const { ref, focusSelf, focusKey } = useFocusable({
focusKey: `${context.id}-list-option-${data.id}`, focusKey: `${context.id}-list-option-${data.id}`,
onEnterPress: data.shortcuts ? undefined : handleAction, onEnterPress: data.shortcuts ? undefined : handleAction,
onFocus: handleFocus, onFocus: handleFocus,

View file

@ -6,7 +6,6 @@ import Shortcuts from "./Shortcuts";
import { Button } from "./options/Button"; import { Button } from "./options/Button";
import { useEffect } from "react"; import { useEffect } from "react";
import { ErrorComponentProps } from "@tanstack/react-router"; import { ErrorComponentProps } from "@tanstack/react-router";
import { mobileCheck } from "../scripts/utils";
export default function Error (data: ErrorComponentProps) export default function Error (data: ErrorComponentProps)
{ {
@ -19,12 +18,15 @@ export default function Error (data: ErrorComponentProps)
return <div ref={ref} className="absolute flex flex-col justify-center items-center w-full h-full gap-4"> return <div ref={ref} className="absolute flex flex-col justify-center items-center w-full h-full gap-4">
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<p className="flex gap-2 items-center text-4xl text-error text-shadow-lg"> <p className="flex gap-2 items-center text-2xl text-error text-shadow-lg">
<TriangleAlert className="size-12" /> <TriangleAlert className="size-12" />
{data.error.message} {data.error.message}
</p> </p>
<p className="flex gap-2 text-lg text-base-content/50 text-shadow-lg">{window.location.href} </p> <p className="flex gap-2 text-base-content/50 text-shadow-lg">{window.location.href} </p>
<Button className="text-2xl! p-6! focusable focusable-primary" id="return" onAction={handleReturn}><Home />Return Home</Button>
{import.meta.env.DEV && <div className="text-center text-base-content/50">{data.error.stack}</div>}
<Button className="text-2xl! focusable focusable-primary" id="return" onAction={handleReturn}><Home />Return Home</Button>
<div className="mobile:hidden bg-gradient"></div> <div className="mobile:hidden bg-gradient"></div>
<div className="mobile:hidden bg-noise"></div> <div className="mobile:hidden bg-noise"></div>
<div className="flex justify-end fixed bottom-4 left-4 right-4"><Shortcuts shortcuts={shortcuts} /></div> <div className="flex justify-end fixed bottom-4 left-4 right-4"><Shortcuts shortcuts={shortcuts} /></div>

View file

@ -2,7 +2,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { ContextList, DialogEntry } from "./ContextDialog"; import { ContextList, DialogEntry } from "./ContextDialog";
import { systemApi } from "../scripts/clientApi"; import { systemApi } from "../scripts/clientApi";
import { useContext, useRef, useState } from "react"; import { useContext, useRef, useState } from "react";
import path from "pathe"; import path, { dirname } from "pathe";
import { Check, Folder, FolderInput, FolderOutput, FolderPlus, HardDrive, Usb, X } from "lucide-react"; import { Check, Folder, FolderInput, FolderOutput, FolderPlus, HardDrive, Usb, X } from "lucide-react";
import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation"; import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { DirType } from "@/shared/constants"; import { DirType } from "@/shared/constants";
@ -12,7 +12,7 @@ import { GamePadButtonCode, Shortcut, useShortcuts } from "../scripts/shortcuts"
import SvgIcon from "./SvgIcon"; import SvgIcon from "./SvgIcon";
import { Button } from "./options/Button"; import { Button } from "./options/Button";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { drivesQuery, filesQuery } from "../scripts/queries"; import queries from "../scripts/queries";
import { FilePickerContext } from "../scripts/contexts"; import { FilePickerContext } from "../scripts/contexts";
import useActiveControl from "../scripts/gamepads"; import useActiveControl from "../scripts/gamepads";
@ -113,12 +113,7 @@ function NewFolderOption (data: { id: string, dirname: string; })
const { refetchFiles } = useContext(FilePickerContext); const { refetchFiles } = useContext(FilePickerContext);
const [name, setName] = useState<string | undefined>(); const [name, setName] = useState<string | undefined>();
const createMutation = useMutation({ const createMutation = useMutation({
mutationKey: ['create', 'folder', data.id], mutationFn: async () => ...queries.system.createFolderMutation(data.id),
{
if (!name) return;
const { error } = await systemApi.api.system.dirs.put({ name, dirname: data.dirname });
if (error) throw error.value;
},
onError: (e) => toast.error(e.message ?? 'Error Creating New Folder'), onError: (e) => toast.error(e.message ?? 'Error Creating New Folder'),
onSuccess: (d, v, r, cx) => onSuccess: (d, v, r, cx) =>
{ {
@ -128,7 +123,7 @@ function NewFolderOption (data: { id: string, dirname: string; })
}); });
return <div className="flex gap-2 grow -ml-2"> return <div className="flex gap-2 grow -ml-2">
<NewFolderInput className="grow" id={`${data.id}-input`} setName={setName} name={name} /> <NewFolderInput className="grow" id={`${data.id}-input`} setName={setName} name={name} />
<Button id={`${data.id}-create`} onAction={e => createMutation.mutate()} type="button" ><FolderPlus /></Button> <Button id={`${data.id}-create`} onAction={e => createMutation.mutate({ name, dirname: data.dirname })} type="button" ><FolderPlus /></Button>
</div>; </div>;
} }
@ -233,8 +228,8 @@ export default function FilePicker (data: {
{ {
const [currentPath, setCurrentPath] = useState<string | undefined>(data.startingPath); const [currentPath, setCurrentPath] = useState<string | undefined>(data.startingPath);
const { data: files, refetch: refetchFiles, isLoading: filesLoading } = useQuery(filesQuery(currentPath, data.id)); const { data: files, refetch: refetchFiles, isLoading: filesLoading } = useQuery(queries.system.filesQuery(currentPath, data.id));
const { data: drives, isLoading: drivesLoading } = useQuery(drivesQuery); const { data: drives, isLoading: drivesLoading } = useQuery(queries.system.drivesQuery);
const fullPath = files ? path.join(files.parentPath, files.name) : ''; const fullPath = files ? path.join(files.parentPath, files.name) : '';
const activeDrive = drives?.filter(d => !!d.mountPoint).sort((a, b) => b.mountPoint!.length - a.mountPoint!.length).filter(d => fullPath.startsWith(d.mountPoint!))[0]; const activeDrive = drives?.filter(d => !!d.mountPoint).sort((a, b) => b.mountPoint!.length - a.mountPoint!.length).filter(d => fullPath.startsWith(d.mountPoint!))[0];

View file

@ -11,14 +11,13 @@ function FilterCat (
id: string; id: string;
children?: any; children?: any;
active: boolean; active: boolean;
onFocus: () => void;
hasFocusedPeer: boolean; hasFocusedPeer: boolean;
} & FilterOption, } & FilterOption & FocusParams,
) )
{ {
const { ref, focusSelf, focused } = useFocusable({ const { ref, focusSelf } = useFocusable({
focusKey: data.id, focusKey: data.id,
onFocus: data.onFocus, onFocus: (l, p, details) => data.onFocus?.(data.id, ref.current, details),
onEnterPress: data.onAction onEnterPress: data.onAction
}); });

View file

@ -2,20 +2,75 @@ import { setFocus } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames"; import classNames from "classnames";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { useGlobalFocus } from "../scripts/spatialNavigation"; import { useGlobalFocus } from "../scripts/spatialNavigation";
import { JSX, RefObject, useMemo, useState } from "react";
import { useEventListener } from "usehooks-ts";
function ScrollDot (data: { index: number; parent: RefObject<HTMLElement | null>, peers: HTMLElement[]; })
{
const [focused, setFocused] = useState(false);
useEventListener('scrollend', () =>
{
if (!data.parent.current) return;
const center = data.parent.current.scrollLeft + data.parent.current.clientWidth / 2;
// find child closest to center
const closest = data.peers.reduce((closest, child) =>
{
const childCenter = child.offsetLeft + child.offsetWidth / 2;
const closestCenter = closest.offsetLeft + closest.offsetWidth / 2;
return Math.abs(childCenter - center) < Math.abs(closestCenter - center)
? child
: closest;
});
setFocused(closest === data.peers[data.index]);
}, data.parent as any);
return <button key={data.index} onClick={(e) =>
{
data.peers[data.index].scrollIntoView({ behavior: 'smooth', inline: 'center' });
}}
className={twMerge("cursor-pointer rounded-full size-2 bg-base-content/40 transition-all", classNames({
"size-3 bg-base-content drop-shadow-lg drop-shadow-base-300/40": focused
}))}></button>;
}
export default function FocusDots (data: { export default function FocusDots (data: {
elements: string[]; elements?: string[] | undefined;
scrollElement?: RefObject<HTMLElement | null>;
}) })
{ {
const focusedKey = useGlobalFocus();
return <div className="divider opacity-20"><div className="flex gap-2 py-6 justify-center items-center h-3">{data.elements.map((em, i) => const focusedKey = useGlobalFocus();
let elements = useMemo(() =>
{ {
const focused = em === focusedKey; if (data.elements)
return <button key={i} onClick={(e) => setFocus(em, { nativeEvent: e.nativeEvent })} {
className={twMerge("cursor-pointer rounded-full size-2 bg-base-content/40 transition-all", classNames({ return data.elements.map((em, i) =>
"size-3 bg-base-content drop-shadow-lg drop-shadow-base-300/40": focused {
}))}></button>; const focused = em === focusedKey;
})}</div></div>; return <button key={i} onClick={(e) => setFocus(em, { nativeEvent: e.nativeEvent })}
className={twMerge("cursor-pointer rounded-full size-2 bg-base-content/40 transition-all", classNames({
"size-3 bg-base-content drop-shadow-lg drop-shadow-base-300/40": focused
}))}></button>;
});
} else if (data.scrollElement?.current)
{
const childrenArray = Array.from(data.scrollElement.current.children);
return childrenArray.map((c, i) =>
{
return <ScrollDot parent={data.scrollElement!} index={i} peers={childrenArray as HTMLElement[]} />;
});
} else
{
return [];
}
}, [data.elements, data.scrollElement?.current]);
return <div className="divider opacity-20">
<div className="flex gap-2 py-6 justify-center items-center h-3">{elements}</div>
</div>;
} }

View file

@ -1,13 +1,14 @@
import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query"; import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { GameMetaExtra, CardList } from "./CardList"; import { GameMetaExtra, CardList } from "./CardList";
import { FrontEndId, GameListFilterType, RPC_URL } from "@shared/constants"; import { FrontEndGameType, FrontEndId, GameListFilterType, RPC_URL } from "@shared/constants";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { SaveSource } from "../scripts/spatialNavigation"; import { SaveSource } from "../scripts/spatialNavigation";
import { rommApi } from "../scripts/clientApi";
import { HardDrive } from "lucide-react"; import { HardDrive } from "lucide-react";
import { JSX } from "react"; import { JSX, useContext } from "react";
import { GameCardFocusHandler } from "./CardElement"; import { GameCardFocusHandler } from "./CardElement";
import { useLocalSetting } from "../scripts/utils"; import { useLocalSetting } from "../scripts/utils";
import { AnimatedBackgroundContext } from "../scripts/contexts";
import queries from "../scripts/queries";
export interface GameListParams export interface GameListParams
{ {
@ -18,19 +19,16 @@ export interface GameListParams
onGameSelect?: (id: FrontEndId, source: string | null, sourceId: string | null) => void; onGameSelect?: (id: FrontEndId, source: string | null, sourceId: string | null) => void;
onFocus?: GameCardFocusHandler; onFocus?: GameCardFocusHandler;
className?: string; className?: string;
finalElement?: JSX.Element;
saveChildFocus?: "session" | "local";
} }
export function GameList (data: GameListParams) export function GameList (data: GameListParams)
{ {
const games = useSuspenseQuery({ const games = useSuspenseQuery(queries.romm.allGamesQuery(data.filters));
queryKey: ['games', data.filters ?? 'all'],
queryFn: () => rommApi.api.romm.games.get({
query: data.filters
}).then(d => d.data)
});
const navigator = useNavigate(); const navigator = useNavigate();
const queryClient = useQueryClient();
const blur = useLocalSetting('backgroundBlur'); const blur = useLocalSetting('backgroundBlur');
const backgroundContext = useContext(AnimatedBackgroundContext);
const handleFocus = (id: FrontEndId, source: string | null, sourceId: string | null) => const handleFocus = (id: FrontEndId, source: string | null, sourceId: string | null) =>
{ {
@ -39,11 +37,11 @@ export function GameList (data: GameListParams)
{ {
try try
{ {
const screenshotUrl = new URL(`${RPC_URL(__HOST__)}${game.paths_screenshots[new Date().getMinutes() % game.paths_screenshots.length]}`); const screenshotUrl = game.paths_screenshots && game.paths_screenshots.length > 0 ? new URL(`${RPC_URL(__HOST__)}${game.paths_screenshots[new Date().getMinutes() % game.paths_screenshots.length]}`) : undefined;
const coverUrl = new URL(`${RPC_URL(__HOST__)}${game.path_cover}`); const coverUrl = new URL(`${RPC_URL(__HOST__)}${game.path_cover}`);
const previewUrl = blur ? coverUrl : screenshotUrl; const previewUrl = blur ? coverUrl : (screenshotUrl ?? coverUrl);
previewUrl.searchParams.delete('ts'); previewUrl.searchParams.delete('ts');
data.setBackground?.(previewUrl.href); data.setBackground?.(previewUrl.href) ?? backgroundContext.setBackground(previewUrl.href);
} catch } catch
{ {
@ -51,10 +49,10 @@ export function GameList (data: GameListParams)
} }
}; };
function handleDefaultSelect (id: FrontEndId, source: string | null, sourceId: string | null) function handleDefaultSelect (g: FrontEndGameType)
{ {
SaveSource('details'); SaveSource('details', { search: { focus: g.slug ?? `game-${g.id}` } });
navigator({ to: '/game/$source/$id', params: { id: String(sourceId ?? id.id), source: source ?? id.source }, viewTransition: { types: ['zoom-in'] } }); navigator({ to: '/game/$source/$id', params: { id: String(g.source_id ?? g.id.id), source: g.source ?? g.id.source }, viewTransition: { types: ['zoom-in'] } });
}; };
return ( return (
@ -65,6 +63,8 @@ export function GameList (data: GameListParams)
grid={data.grid} grid={data.grid}
className={data.className} className={data.className}
onGameFocus={data.onFocus} onGameFocus={data.onFocus}
finalElement={data.finalElement}
saveChildFocus={data.saveChildFocus}
games={games.data?.games games={games.data?.games
.map( .map(
(g) => (g) =>
@ -92,7 +92,7 @@ export function GameList (data: GameListParams)
), ),
previewUrl: previewUrl.href, previewUrl: previewUrl.href,
badges: badges, badges: badges,
onSelect: () => data.onGameSelect ? data.onGameSelect(g.id, g.source, g.source_id) : handleDefaultSelect(g.id, g.source, g.source_id), onSelect: () => data.onGameSelect ? data.onGameSelect(g.id, g.source, g.source_id) : handleDefaultSelect(g),
onFocus: () => handleFocus(g.id, g.source, g.source_id) onFocus: () => handleFocus(g.id, g.source, g.source_id)
} satisfies GameMetaExtra; } satisfies GameMetaExtra;
}, },

View file

@ -25,7 +25,7 @@ import { useQuery } from "@tanstack/react-query";
import { getCurrentUserApiUsersMeGetOptions, statsApiStatsGetOptions } from "@clients/romm/@tanstack/react-query.gen"; import { getCurrentUserApiUsersMeGetOptions, statsApiStatsGetOptions } from "@clients/romm/@tanstack/react-query.gen";
import { RPC_URL } from "../../shared/constants"; import { RPC_URL } from "../../shared/constants";
import { JSX, useEffect, useRef } from "react"; import { JSX, useEffect, useRef } from "react";
import { SaveSource, useFocusableDynamic } from "../scripts/spatialNavigation"; import { SaveSource } from "../scripts/spatialNavigation";
import { systemApi } from "../scripts/clientApi"; import { systemApi } from "../scripts/clientApi";
import { Router } from ".."; import { Router } from "..";
@ -228,25 +228,12 @@ function BatteryStatus ()
export function HeaderAccounts (data: { accounts?: HeaderAccount[]; }) export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
{ {
const rommOnline = useQuery({
...statsApiStatsGetOptions(),
refetchInterval: 30000,
retry: false,
});
const user = useQuery({ const user = useQuery({
...getCurrentUserApiUsersMeGetOptions(), ...getCurrentUserApiUsersMeGetOptions(),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
retry: 1 retry: 1
}); });
let indicator = "status-neutral";
if (user.isError)
{
indicator = "status-error";
} else if (!user.isPending && rommOnline.isSuccess)
{
indicator = "status-success";
}
const accounts: HeaderAccount[] = [{ const accounts: HeaderAccount[] = [{
id: 'romm', previewUrl: [ id: 'romm', previewUrl: [
`${RPC_URL(__HOST__)}/api/romm/assets/logos/romm_logo_xbox_one_square.svg`, `${RPC_URL(__HOST__)}/api/romm/assets/logos/romm_logo_xbox_one_square.svg`,

View file

@ -0,0 +1,35 @@
import { setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { FOCUS_KEYS } from "../scripts/types";
import { useIntersectionObserver } from "usehooks-ts";
export default function LoadMoreButton (data: { isFetching: boolean; lastId?: string; } & FocusParams & InteractParams)
{
const handleAction = (e?: Event) =>
{
data.onAction?.(e);
if (data.lastId && focused)
setFocus(FOCUS_KEYS.GAME_CARD(data.lastId));
};
const { ref, focusKey, focused } = useFocusable({
focusKey: 'load-more-btn',
onFocus: (_l, _p, details) => data.onFocus?.(focusKey, ref.current, details),
onEnterPress: handleAction
});
const { ref: intersct } = useIntersectionObserver({
onChange: (isIntersecting, entry) =>
{
if (isIntersecting)
{
handleAction();
}
}
});
return <div ref={(r) =>
{
ref.current = r;
intersct(r);
}} className='flex bg-base-100 game-card focusable focusable-accent focusable-hover text-2xl justify-center items-center cursor-pointer' onClick={e => handleAction(e.nativeEvent)} id='load-more-btn'>{data.isFetching ? <span className="loading loading-spinner loading-xl"></span> : "Load More"}</div>;
}

View file

@ -17,6 +17,7 @@ export function PlatformsList (data: {
onFocus?: GameCardFocusHandler; onFocus?: GameCardFocusHandler;
grid?: boolean; grid?: boolean;
onSelect?: (source: string, id: string) => void; onSelect?: (source: string, id: string) => void;
saveChildFocus?: "session" | "local";
}) })
{ {
const isMobile = mobileCheck(); const isMobile = mobileCheck();
@ -85,6 +86,7 @@ export function PlatformsList (data: {
return ( return (
<CardList <CardList
type="platform" type="platform"
saveChildFocus={data.saveChildFocus}
id={data.id} id={data.id}
grid={data.grid} grid={data.grid}
className={twMerge('*:aspect-8/10! md:py-12', data.className)} className={twMerge('*:aspect-8/10! md:py-12', data.className)}

View file

@ -1,4 +1,4 @@
import { CSSProperties, JSX } from "react"; import { CSSProperties } from "react";
import { twMerge } from 'tailwind-merge'; import { twMerge } from 'tailwind-merge';
import { Button, ButtonStyle } from "./options/Button"; import { Button, ButtonStyle } from "./options/Button";
@ -12,7 +12,7 @@ export function RoundButton (data: {
} & InteractParams & FocusParams) } & InteractParams & FocusParams)
{ {
return ( return (
<Button cssStyle={data.cssStyle} onFocus={data.onFocus} id={data.id} style={data.style} className={twMerge("rounded-full", data.external && "focusable focusable-primary focusable-hover", data.className)} onAction={data.onAction}> <Button cssStyle={data.cssStyle} onFocus={data.onFocus} id={data.id} style={data.style} className={twMerge("rounded-full aspect-square", data.external && "focusable focusable-primary focusable-hover", data.className)} onAction={data.onAction}>
{data.children} {data.children}
</Button> </Button>

View file

@ -1,16 +1,19 @@
import { RPC_URL } from "@/shared/constants"; import { RPC_URL } from "@/shared/constants";
import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation"; import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import FocusDots from "./FocusDots"; import FocusDots from "./FocusDots";
import { scrollIntoNearestParent, useDragScroll } from "../scripts/utils"; import { scrollIntoNearestParent, useDragScroll } from "../scripts/utils";
import { Fullscreen } from "lucide-react"; import { Fullscreen } from "lucide-react";
import Carousel from "./Carousel";
import { ContextDialog } from "./ContextDialog";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "../scripts/shortcuts";
function Screenshot (data: { path: string; index: number; setFocused?: (index: number) => void; }) function Screenshot (data: { path: string; index: number; setFocused?: (index: number) => void; } & InteractParams)
{ {
const imageRef = useRef<HTMLImageElement>(null); const imageRef = useRef<HTMLImageElement>(null);
const { ref, focused, focusSelf } = useFocusable({ const { ref, focusSelf } = useFocusable({
focusKey: `screenshot-${data.index}`, focusKey: `screenshot-${data.index}`,
onEnterPress: () => (ref.current as HTMLElement).requestFullscreen(), onEnterPress: () => data.onAction?.(),
onFocus: (e, p, details) => onFocus: (e, p, details) =>
{ {
data.setFocused?.(data.index); data.setFocused?.(data.index);
@ -19,31 +22,109 @@ function Screenshot (data: { path: string; index: number; setFocused?: (index: n
}); 4096; }); 4096;
return <div ref={ref} className="group relative flex min-w-fit aspect-video max-h-[60vh] rounded-3xl focusable focusable-accent not-focused:cursor-pointer overflow-hidden"> return <div ref={ref} className="group relative flex min-w-fit aspect-video max-h-[60vh] rounded-3xl focusable focusable-accent not-focused:cursor-pointer overflow-hidden">
<img ref={imageRef} draggable={false} className="object-cover w-full h-full" onClick={e => focusSelf({ nativeEvent: e.nativeEvent })} src={`${RPC_URL(__HOST__)}${data.path}`} loading="lazy" /> <img ref={imageRef} draggable={false} className="object-cover w-full h-full" onClick={e => focusSelf({ nativeEvent: e.nativeEvent })} src={`${RPC_URL(__HOST__)}${data.path}`} loading="lazy" />
<div className="absolute flex justify-center items-center bottom-2 right-2 size-10 rounded-full bg-base-100 hover:bg-base-content hover:text-base-300 cursor-pointer opacity-60 not-control-mouse:hidden invisible group-has-hover:visible" onClick={() => imageRef.current?.requestFullscreen()}> <Fullscreen /> </div> <div className="absolute flex justify-center items-center bottom-2 right-2 size-10 rounded-full bg-base-100 hover:bg-base-content hover:text-base-300 cursor-pointer opacity-60 not-control-mouse:hidden invisible group-has-hover:visible" onClick={e => data.onAction?.(e.nativeEvent)}> <Fullscreen /> </div>
</div>; </div>;
} }
export default function Screenshots (data: { screenshots: string[]; } & FocusParams) export default function Screenshots (data: { screenshots: string[]; } & FocusParams)
{ {
const scrollRef = useRef(null); const [preview, setPreview] = useState<number | undefined>(undefined);
const { ref, focusKey } = useFocusable({ const scrollRef = useRef<HTMLDivElement>(null);
const { ref, focusKey, focused, hasFocusedChild } = useFocusable({
focusKey: 'screenshot-list', focusKey: 'screenshot-list',
trackChildren: true,
onFocus: (e, p, details) => onFocus: (e, p, details) =>
{ {
data.onFocus?.(focusKey, ref.current, details); data.onFocus?.(focusKey, ref.current, details);
} }
}); });
useEffect(() =>
{
if ((focused || hasFocusedChild) && scrollRef.current)
{
const closest = findClosestElementToCenter(scrollRef.current);
const closestIndex = Array.from(scrollRef.current.children).indexOf(closest);
setFocus(`screenshot-${closestIndex}`);
}
}, [focused, hasFocusedChild, scrollRef.current]);
const findClosestElementToCenter = (element: HTMLDivElement) =>
{
const center = element.scrollLeft + element.clientWidth / 2;
const children = Array.from(element.children) as HTMLElement[];
// find child closest to center
return children.reduce((closest, child) =>
{
const childCenter = child.offsetLeft + child.offsetWidth / 2;
const closestCenter = closest.offsetLeft + closest.offsetWidth / 2;
return Math.abs(childCenter - center) < Math.abs(closestCenter - center)
? child
: closest;
});
};
useEffect(() =>
{
if (preview !== undefined && scrollRef.current)
{
Array.from(scrollRef.current.children)[preview].scrollIntoView({ inline: 'center', behavior: 'instant' });
}
}, [preview]);
const handleScroll = (dir: number, element: HTMLDivElement) =>
{
const current = findClosestElementToCenter(element);
const next = (dir > 0 ? current.nextElementSibling : current.previousElementSibling) as HTMLElement | null;
if (!next) return;
// scroll so next element is centered
element.scrollTo({
left: next.offsetLeft - element.clientWidth / 2 + next.offsetWidth / 2,
behavior: "smooth"
});
};
useShortcuts(`screenshots-context-dialog`, () => [
{
button: GamePadButtonCode.Left,
label: "Left",
action: () =>
{
if (preview === undefined) return;
setPreview((data.screenshots.length + preview - 1) % data.screenshots.length);
}
},
{
button: GamePadButtonCode.Right,
label: "Right",
action: () =>
{
if (preview === undefined) return;
setPreview((preview + 1) % data.screenshots.length);
}
}
], [preview, focusKey]);
useDragScroll(scrollRef); useDragScroll(scrollRef);
return <div ref={ref} className="flex flex-col w-full z-0 min-h-0"> return <div ref={ref} className="flex flex-col w-full z-0 min-h-0">
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<div <Carousel scrollHandler={handleScroll} scrollRef={scrollRef} rootClassName="h-full" className="flex gap-6 px-16 py-2 overflow-x-scroll no-scrollbar justify-center-safe h-full" >
ref={scrollRef} {data.screenshots.map((s, i) => <Screenshot key={s} index={i} path={s} onAction={() => setPreview(i)} />)}
className="flex gap-6 px-16 py-2 sm:overflow-scroll md:overflow-hidden no-scrollbar justify-center-safe" </Carousel>
> <FocusDots scrollElement={scrollRef} />
{data.screenshots.map((s, i) => <Screenshot key={s} index={i} path={s} />)}
</div>
<FocusDots elements={data.screenshots.map((_, i) => `screenshot-${i}`)} />
</FocusContext> </FocusContext>
{preview !== undefined && <ContextDialog id="screenshots" close={() =>
{
setFocus(`screenshot-${preview}`);
setPreview(undefined);
}} open={true}>
<img draggable={false} className="object-cover w-full h-full rounded-2xl" src={`${RPC_URL(__HOST__)}${data.screenshots[preview]}`} loading="lazy" />
</ContextDialog>}
</div>; </div>;
} }

View file

@ -5,7 +5,7 @@ import
useFocusable, useFocusable,
} from "@noriginmedia/norigin-spatial-navigation"; } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames"; import classNames from "classnames";
import { GamePadButtonCode, Shortcut, useShortcuts } from "@/mainview/scripts/shortcuts"; import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts";
import { CSSProperties } from "react"; import { CSSProperties } from "react";
export type ButtonStyle = 'base' | 'accent' | 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'; export type ButtonStyle = 'base' | 'accent' | 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error';

View file

@ -1,14 +1,14 @@
import { useState } from "react"; import { useState } from "react";
import { PathSettingsOptionBase, PathSettingsOptionParams } from "./PathSettingsOption"; import { PathSettingsOptionBase, PathSettingsOptionParams } from "./PathSettingsOption";
import { useMutation } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import { changeDownloadsMutation } from "@/mainview/scripts/queries"; import queries from "@/mainview/scripts/queries";
export default function DownloadDirectoryOption (data: PathSettingsOptionParams) export default function DownloadDirectoryOption (data: PathSettingsOptionParams)
{ {
const [localValue, setLocalValue] = useState<string | undefined>(); const [localValue, setLocalValue] = useState<string | undefined>();
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const setSettingMutation = useMutation({ const setSettingMutation = useMutation({
...changeDownloadsMutation, ...queries.settings.changeDownloadsMutation,
onSuccess: (d, v, r, cx) => onSuccess: (d, v, r, cx) =>
{ {
setDirty(r !== localValue); setDirty(r !== localValue);

View file

@ -1,6 +1,5 @@
import { FocusEventHandler, HTMLInputAutoCompleteAttribute, HTMLInputTypeAttribute, JSX, useRef, useState } from "react"; import { FocusEventHandler, HTMLInputAutoCompleteAttribute, HTMLInputTypeAttribute, JSX, useState } from "react";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { useOptionContext } from "./OptionSpace";
import { useFocusable } from "@noriginmedia/norigin-spatial-navigation"; import { useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { ContextDialog, ContextList, DialogEntry } from "../ContextDialog"; import { ContextDialog, ContextList, DialogEntry } from "../ContextDialog";
import { ChevronDown } from "lucide-react"; import { ChevronDown } from "lucide-react";
@ -25,15 +24,9 @@ export function OptionDropdown (data: {
setOpen(true); setOpen(true);
}; };
const handleClose = () => setOpen(false); const handleClose = () => setOpen(false);
const { ref, focused, focusKey } = useFocusable({ const { ref } = useFocusable({
focusKey: data.name, onEnterPress: handlePress focusKey: data.name, onEnterPress: handlePress
}); });
const inputRef = useRef<HTMLInputElement>(null);
const option = useOptionContext({
onOptionEnterPress: handlePress,
});
const valueIndex = data.value ? data.values?.indexOf(data.value) : -1;
return ( return (
<> <>

View file

@ -28,7 +28,7 @@ export function OptionInput (data: {
inputRef.current?.focus(); inputRef.current?.focus();
} }
}; };
const { ref, focused } = useFocusable({ const { ref } = useFocusable({
focusKey: data.name, onEnterPress: handlePress focusKey: data.name, onEnterPress: handlePress
}); });
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);

View file

@ -41,7 +41,7 @@ export function OptionSpace (data: {
}) })
{ {
const eventTarget = useMemo(() => new EventTarget(), []); const eventTarget = useMemo(() => new EventTarget(), []);
const { ref, focused, focusSelf, focusKey, hasFocusedChild } = useFocusable({ const { ref, focused, focusSelf, focusKey } = useFocusable({
focusKey: data.id, focusKey: data.id,
focusable: data.focusable !== false, focusable: data.focusable !== false,
trackChildren: true, trackChildren: true,

View file

@ -1,14 +1,14 @@
import { HTMLInputTypeAttribute, JSX, useCallback, useState } from "react"; import { HTMLInputTypeAttribute, JSX, useEffect, useState } from "react";
import { SettingsType } from "../../../shared/constants"; import { SettingsType } from "../../../shared/constants";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import { OptionSpace } from "./OptionSpace"; import { OptionSpace } from "./OptionSpace";
import { OptionInput } from "./OptionInput"; import { OptionInput } from "./OptionInput";
import { settingsApi } from "../../scripts/clientApi";
import { Button } from "./Button"; import { Button } from "./Button";
import { FileSearchCorner, FolderSearch, Pen, Save } from "lucide-react"; import { FileSearchCorner, FolderSearch, Pen, Save } from "lucide-react";
import { ContextDialog } from "../ContextDialog"; import { ContextDialog } from "../ContextDialog";
import FilePicker from "../FilePicker"; import FilePicker from "../FilePicker";
import { setFocus } from "@noriginmedia/norigin-spatial-navigation"; import { setFocus } from "@noriginmedia/norigin-spatial-navigation";
import queries from "@/mainview/scripts/queries";
type KeysWithValueAssignableTo<T, Value> = { type KeysWithValueAssignableTo<T, Value> = {
[K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never; [K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never;
@ -32,14 +32,8 @@ export function PathSettingsOption (data: PathSettingsOptionParams)
{ {
const [localValue, setLocalValue] = useState<string | undefined>(); const [localValue, setLocalValue] = useState<string | undefined>();
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const setSettingMutation = useMutation({ const setMutation = useMutation({
mutationKey: ["setting", data.id], ...queries.settings.setSettingMutation(data.id),
mutationFn: async (value: any) =>
{
const response = await settingsApi.api.settings({ id: data.id! }).post({ value });
if (response.error) throw response.error;
return response.data;
},
onSuccess: (d, v, r, cx) => onSuccess: (d, v, r, cx) =>
{ {
setDirty(r !== localValue); setDirty(r !== localValue);
@ -51,7 +45,7 @@ export function PathSettingsOption (data: PathSettingsOptionParams)
label={data.label} label={data.label}
id={data.id} id={data.id}
type={data.type} type={data.type}
save={setSettingMutation.mutate} save={setMutation.mutate}
localValue={localValue} localValue={localValue}
allowNewFolderCreation={data.allowNewFolderCreation} allowNewFolderCreation={data.allowNewFolderCreation}
setLocalValue={(v) => setLocalValue={(v) =>
@ -69,22 +63,17 @@ export function PathSettingsOptionBase (data: PathSettingsOptionParams & {
}) })
{ {
const [isBrowsing, setIsBrowsing] = useState(false); const [isBrowsing, setIsBrowsing] = useState(false);
const { data: defaultValue } = useQuery({ const { data: defaultValue } = useQuery(queries.settings.getSettingQuery(data.id));
enabled: !!data.id,
queryKey: ["setting", data.id],
queryFn: async () =>
{
const { data: value, error } = await settingsApi.api.settings({ id: data.id! }).get();
if (error) throw error;
if (!data.isDirty)
{
data.setLocalValue(String(value.value));
}
return value.value;
},
});
const changed = defaultValue !== data.localValue; const changed = defaultValue !== data.localValue;
useEffect(() =>
{
if (!data.isDirty)
{
data.setLocalValue(String(defaultValue));
}
}, [data.isDirty, defaultValue]);
const handleSelectPath = (path: string) => const handleSelectPath = (path: string) =>
{ {
data.setLocalValue(path); data.setLocalValue(path);

View file

@ -3,7 +3,7 @@ import { SettingsType } from "../../../shared/constants";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import { OptionSpace } from "./OptionSpace"; import { OptionSpace } from "./OptionSpace";
import { OptionInput } from "./OptionInput"; import { OptionInput } from "./OptionInput";
import { settingsApi } from "../../scripts/clientApi"; import queries from "@/mainview/scripts/queries";
type KeysWithValueAssignableTo<T, Value> = { type KeysWithValueAssignableTo<T, Value> = {
[K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never; [K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never;
@ -20,36 +20,15 @@ export function SettingsOption (data: {
{ {
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const [localValue, setLocalValue] = useState<string | undefined>(); const [localValue, setLocalValue] = useState<string | undefined>();
useQuery({ useQuery(queries.settings.getSettingQuery(data.id));
enabled: !!data.id, const setMutation = useMutation(queries.settings.setSettingMutation(data.id));
queryKey: ["setting", data.id],
queryFn: async () =>
{
const { data: value, error } = await settingsApi.api.settings({ id: data.id! }).get();
if (error) throw error;
if (!dirty)
{
setLocalValue(String(value.value));
}
return value.value;
},
});
const setSettingMutation = useMutation({
mutationKey: ["setting", data.id],
mutationFn: async (value: any) =>
{
const response = await settingsApi.api.settings({ id: data.id! }).post({ value });
if (response.error) throw response.error;
return response.data;
}
});
const handleSave = useCallback(() => const handleSave = useCallback(() =>
{ {
if (dirty) if (dirty)
{ {
setDirty(false); setDirty(false);
setSettingMutation.mutate(localValue); setMutation.mutate(localValue);
} }
}, [dirty, setDirty, localValue]); }, [dirty, setDirty, localValue]);

View file

@ -12,6 +12,7 @@ import { Router } from "@/mainview";
import { StoreEmulatorCard } from "./StoreEmulatorCard"; import { StoreEmulatorCard } from "./StoreEmulatorCard";
import { FOCUS_KEYS } from "@/mainview/scripts/types"; import { FOCUS_KEYS } from "@/mainview/scripts/types";
import { FrontEndEmulator } from "@/shared/constants"; import { FrontEndEmulator } from "@/shared/constants";
import Carousel from "../Carousel";
function SeeAllCard (data: { id: string; onAction: () => void; onFocus?: (details: { node: HTMLElement, instant: boolean; }) => void; }) function SeeAllCard (data: { id: string; onAction: () => void; onFocus?: (details: { node: HTMLElement, instant: boolean; }) => void; })
{ {
@ -34,7 +35,7 @@ function SeeAllCard (data: { id: string; onAction: () => void; onFocus?: (detail
export function EmulatorsSection (data: { export function EmulatorsSection (data: {
id: string; id: string;
emulators: FrontEndEmulator[]; emulators?: FrontEndEmulator[];
onSelect?: (id: string, focusKey: string) => void; onSelect?: (id: string, focusKey: string) => void;
header?: any; header?: any;
} & FocusParams) } & FocusParams)
@ -60,17 +61,19 @@ export function EmulatorsSection (data: {
</h2> </h2>
</>} </>}
</div> </div>
<div ref={containerRef} className="flex *:min-w-[18rem] overflow-y-hidden overflow-x-scroll scrollbar-none py-2 px-4 gap-4 select-none">
<Carousel scrollRef={containerRef} className="flex *:min-w-[18rem] overflow-y-hidden overflow-x-scroll scrollbar-none py-2 px-4 gap-4 select-none">
{data.emulators?.map((em) => ( {data.emulators?.map((em) => (
<StoreEmulatorCard id={`${data.id}-${em.name}`} key={em.name} emulator={em} onSelect={(id, focusKey) => data.onSelect?.(em.name, focusKey)} onFocus={({ node, details }) => <StoreEmulatorCard id={`${data.id}-${em.name}`} key={em.name} emulator={em} onSelect={(id, focusKey) => data.onSelect?.(em.name, focusKey)} onFocus={({ node, details }) =>
{ {
scrollIntoNearestParent(node, { behavior: details.instant ? 'instant' : 'smooth' }); scrollIntoNearestParent(node, { behavior: details.instant ? 'instant' : 'smooth' });
}} /> }} />
))} )) ?? Array.from({ length: 8 }).map((_, i) => <div key={i} className="skeleton h-38 w-full rounded-4xl" />)}
<SeeAllCard id={`${FOCUS_KEYS.EMULATOR_SECTION}-see-all`} onAction={() => Router.navigate({ to: '/store/tab/emulators' })} onFocus={({ node, instant }) => scrollIntoNearestParent(node, { behavior: instant ? 'instant' : 'smooth' })} /> <SeeAllCard id={`${FOCUS_KEYS.EMULATOR_SECTION}-see-all`} onAction={() => Router.navigate({ to: '/store/tab/emulators' })} onFocus={({ node, instant }) => scrollIntoNearestParent(node, { behavior: instant ? 'instant' : 'smooth' })} />
</div> </Carousel>
</section> </section>
{!!data.emulators && <FocusDots elements={data.emulators.map(e => FOCUS_KEYS.EMULATOR_CARD(e.name))} />} <FocusDots elements={data.emulators?.map(e => FOCUS_KEYS.EMULATOR_CARD(e.name))} />
</FocusContext.Provider> </FocusContext.Provider>
); );
} }

View file

@ -4,15 +4,16 @@ import
useFocusable, useFocusable,
FocusContext, FocusContext,
} from "@noriginmedia/norigin-spatial-navigation"; } from "@noriginmedia/norigin-spatial-navigation";
import { Gamepad2 } from "lucide-react"; import { Gamepad2, Star } from "lucide-react";
import { useDragScroll } from "@/mainview/scripts/utils"; import { useDragScroll } from "@/mainview/scripts/utils";
import FocusDots from "../FocusDots"; import FocusDots from "../FocusDots";
import { FrontEndGameType, FrontEndId } from "@/shared/constants"; import { FrontEndGameType, FrontEndId } from "@/shared/constants";
import FrontEndGameCard from "../FrontEndGameCard"; import FrontEndGameCard from "../FrontEndGameCard";
import { FOCUS_KEYS } from "@/mainview/scripts/types"; import { FOCUS_KEYS } from "@/mainview/scripts/types";
import Carousel from "../Carousel";
export function GamesSection ({ games, onSelect, onFocus }: { export function GamesSection ({ games, onSelect, onFocus }: {
games: FrontEndGameType[]; games?: FrontEndGameType[];
onSelect?: (id: FrontEndId, focusKey: string) => void; onSelect?: (id: FrontEndId, focusKey: string) => void;
} & FocusParams) } & FocusParams)
{ {
@ -33,17 +34,17 @@ export function GamesSection ({ games, onSelect, onFocus }: {
<h2 className="font-bold uppercase tracking-widest text-accent grow"> <h2 className="font-bold uppercase tracking-widest text-accent grow">
Featured Games Featured Games
</h2> </h2>
<div className="badge badge-xl badge-accent badge-soft">Curated picks</div> <div className="flex gap-2 bg-accent text-accent-content rounded-full py-1 px-4 font-semibold opacity-80"><Star />Creator Picks</div>
</div> </div>
<div ref={containerRef} className="grid grid-flow-col auto-cols-[18rem] overflow-y-hidden overflow-x-auto hide-scrollbar p-4 gap-4 justify-center-safe"> <Carousel controlsClassName="z-20" scrollRef={containerRef} className="flex *:w-[18rem] *:min-w-[18rem] *:h-[21rem] overflow-y-hidden overflow-x-auto hide-scrollbar p-4 gap-4 justify-center-safe">
{games.map((g, i) => <FrontEndGameCard {games?.map((g, i) => <FrontEndGameCard
key={g.id.id} key={g.id.id}
game={g} game={g}
onAction={() => onSelect?.(g.id, FOCUS_KEYS.GAME_CARD(g.id.id))} onAction={() => onSelect?.(g.id, FOCUS_KEYS.GAME_CARD(g.id.id))}
index={i} />)} index={i} />) ?? Array.from({ length: 8 }).map((_, i) => <div key={i} className="skeleton h-38 w-full" />)}
</div> </Carousel>
</section> </section>
<FocusDots elements={games.map(e => FOCUS_KEYS.GAME_CARD(e.id.id))} /> <FocusDots elements={games?.map(e => FOCUS_KEYS.GAME_CARD(e.id.id)) ?? []} />
</FocusContext.Provider> </FocusContext.Provider>
); );
} }

View file

@ -1,4 +1,5 @@
import { storeApi } from "@/mainview/scripts/clientApi";
import queries from "@/mainview/scripts/queries";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { Joystick, LibraryBig, Save, TriangleAlert } from "lucide-react"; import { Joystick, LibraryBig, Save, TriangleAlert } from "lucide-react";
@ -14,14 +15,7 @@ export function StatsSection ({
}: StatsSectionProps) }: StatsSectionProps)
{ {
const { data: stats } = useQuery({ const { data: stats } = useQuery(queries.store.storeGetStatsQuery);
queryKey: ['store', 'stats'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.stats.get();
if (error) throw error;
return data;
}
});
return ( return (
<section className="px-6 pt-3 pb-4"> <section className="px-6 pt-3 pb-4">

View file

@ -9,6 +9,7 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './../routes/__root' import { Route as rootRouteImport } from './../routes/__root'
import { Route as GamesRouteImport } from './../routes/games'
import { Route as SettingsRouteRouteImport } from './../routes/settings/route' import { Route as SettingsRouteRouteImport } from './../routes/settings/route'
import { Route as IndexRouteImport } from './../routes/index' import { Route as IndexRouteImport } from './../routes/index'
import { Route as SettingsInterfaceRouteImport } from './../routes/settings/interface' import { Route as SettingsInterfaceRouteImport } from './../routes/settings/interface'
@ -27,6 +28,11 @@ import { Route as GameSourceIdRouteImport } from './../routes/game/$source.$id'
import { Route as EmbeddedSourceIdRouteImport } from './../routes/embedded.$source.$id' import { Route as EmbeddedSourceIdRouteImport } from './../routes/embedded.$source.$id'
import { Route as StoreDetailsEmulatorIdRouteImport } from './../routes/store/details.emulator.$id' import { Route as StoreDetailsEmulatorIdRouteImport } from './../routes/store/details.emulator.$id'
const GamesRoute = GamesRouteImport.update({
id: '/games',
path: '/games',
getParentRoute: () => rootRouteImport,
} as any)
const SettingsRouteRoute = SettingsRouteRouteImport.update({ const SettingsRouteRoute = SettingsRouteRouteImport.update({
id: '/settings', id: '/settings',
path: '/settings', path: '/settings',
@ -116,6 +122,7 @@ const StoreDetailsEmulatorIdRoute = StoreDetailsEmulatorIdRouteImport.update({
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'/settings': typeof SettingsRouteRouteWithChildren '/settings': typeof SettingsRouteRouteWithChildren
'/games': typeof GamesRoute
'/store/tab': typeof StoreTabRouteRouteWithChildren '/store/tab': typeof StoreTabRouteRouteWithChildren
'/collection/$id': typeof CollectionIdRoute '/collection/$id': typeof CollectionIdRoute
'/settings/about': typeof SettingsAboutRoute '/settings/about': typeof SettingsAboutRoute
@ -135,6 +142,7 @@ export interface FileRoutesByFullPath {
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'/settings': typeof SettingsRouteRouteWithChildren '/settings': typeof SettingsRouteRouteWithChildren
'/games': typeof GamesRoute
'/collection/$id': typeof CollectionIdRoute '/collection/$id': typeof CollectionIdRoute
'/settings/about': typeof SettingsAboutRoute '/settings/about': typeof SettingsAboutRoute
'/settings/accounts': typeof SettingsAccountsRoute '/settings/accounts': typeof SettingsAccountsRoute
@ -154,6 +162,7 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport __root__: typeof rootRouteImport
'/': typeof IndexRoute '/': typeof IndexRoute
'/settings': typeof SettingsRouteRouteWithChildren '/settings': typeof SettingsRouteRouteWithChildren
'/games': typeof GamesRoute
'/store/tab': typeof StoreTabRouteRouteWithChildren '/store/tab': typeof StoreTabRouteRouteWithChildren
'/collection/$id': typeof CollectionIdRoute '/collection/$id': typeof CollectionIdRoute
'/settings/about': typeof SettingsAboutRoute '/settings/about': typeof SettingsAboutRoute
@ -175,6 +184,7 @@ export interface FileRouteTypes {
fullPaths: fullPaths:
| '/' | '/'
| '/settings' | '/settings'
| '/games'
| '/store/tab' | '/store/tab'
| '/collection/$id' | '/collection/$id'
| '/settings/about' | '/settings/about'
@ -194,6 +204,7 @@ export interface FileRouteTypes {
to: to:
| '/' | '/'
| '/settings' | '/settings'
| '/games'
| '/collection/$id' | '/collection/$id'
| '/settings/about' | '/settings/about'
| '/settings/accounts' | '/settings/accounts'
@ -212,6 +223,7 @@ export interface FileRouteTypes {
| '__root__' | '__root__'
| '/' | '/'
| '/settings' | '/settings'
| '/games'
| '/store/tab' | '/store/tab'
| '/collection/$id' | '/collection/$id'
| '/settings/about' | '/settings/about'
@ -232,6 +244,7 @@ export interface FileRouteTypes {
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
SettingsRouteRoute: typeof SettingsRouteRouteWithChildren SettingsRouteRoute: typeof SettingsRouteRouteWithChildren
GamesRoute: typeof GamesRoute
StoreTabRouteRoute: typeof StoreTabRouteRouteWithChildren StoreTabRouteRoute: typeof StoreTabRouteRouteWithChildren
CollectionIdRoute: typeof CollectionIdRoute CollectionIdRoute: typeof CollectionIdRoute
EmbeddedSourceIdRoute: typeof EmbeddedSourceIdRoute EmbeddedSourceIdRoute: typeof EmbeddedSourceIdRoute
@ -243,6 +256,13 @@ export interface RootRouteChildren {
declare module '@tanstack/react-router' { declare module '@tanstack/react-router' {
interface FileRoutesByPath { interface FileRoutesByPath {
'/games': {
id: '/games'
path: '/games'
fullPath: '/games'
preLoaderRoute: typeof GamesRouteImport
parentRoute: typeof rootRouteImport
}
'/settings': { '/settings': {
id: '/settings' id: '/settings'
path: '/settings' path: '/settings'
@ -404,6 +424,7 @@ const StoreTabRouteRouteWithChildren = StoreTabRouteRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
SettingsRouteRoute: SettingsRouteRouteWithChildren, SettingsRouteRoute: SettingsRouteRouteWithChildren,
GamesRoute: GamesRoute,
StoreTabRouteRoute: StoreTabRouteRouteWithChildren, StoreTabRouteRoute: StoreTabRouteRouteWithChildren,
CollectionIdRoute: CollectionIdRoute, CollectionIdRoute: CollectionIdRoute,
EmbeddedSourceIdRoute: EmbeddedSourceIdRoute, EmbeddedSourceIdRoute: EmbeddedSourceIdRoute,

View file

@ -464,7 +464,7 @@ const assets = new Set<string>([
]); ]);
// Store basePath resolved from Vite config // Store basePath resolved from Vite config
const BASE_PATH = "/"; const BASE_PATH = "./";
/** /**

View file

@ -3,7 +3,14 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="./assets/favicon.ico" /> <meta name="description" content="Retro Game Launcher" />
<link rel="icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/256x256.png" sizes="320x320" />
<link rel="mask-icon" href="/icon.svg" color="#1d232a" />
<meta name="theme-color" content="#605dff" />
<link rel="manifest" href="./manifest.json" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link <link
href="https://fonts.googleapis.com/css2?family=Alan+Sans:wght@300..900&display=swap" href="https://fonts.googleapis.com/css2?family=Alan+Sans:wght@300..900&display=swap"
rel="stylesheet" rel="stylesheet"

View file

@ -5,7 +5,6 @@ import
{ {
createHashHistory, createHashHistory,
createRouter, createRouter,
Link,
RouterProvider, RouterProvider,
} from "@tanstack/react-router"; } from "@tanstack/react-router";
import { routeTree } from "./gen/routeTree.gen"; import { routeTree } from "./gen/routeTree.gen";
@ -17,6 +16,12 @@ import { client as rommClient } from "../clients/romm/client.gen";
import "./scripts/spatialNavigation"; import "./scripts/spatialNavigation";
import NotFound from "./components/NotFound"; import NotFound from "./components/NotFound";
import Error from "./components/Error"; import Error from "./components/Error";
import serviceWorker from './scripts/serviceWorker?worker&url';
if ('serviceWorker' in navigator)
{
navigator.serviceWorker.register(serviceWorker);
}
const hashHistory = createHashHistory({}); const hashHistory = createHashHistory({});

View file

@ -0,0 +1,17 @@
{
"short_name": "GF",
"name": "Gameflow Deck",
"start_url": "/",
"display": "fullscreen",
"theme_color": "#605dff",
"background_color": "#1d232a",
"description": "Retro Game Launcher",
"icons": [
{
"src": "/256x256.png",
"sizes": "320x320",
"type": "image/png"
}
],
"lang": "en"
}

BIN
src/mainview/public/256x256.png (Stored with Git LFS) Normal file

Binary file not shown.

View file

@ -1,12 +1,11 @@
import { keepPreviousData, queryOptions } from "@tanstack/react-query"; import { keepPreviousData, queryOptions } from "@tanstack/react-query";
import { getRomApiRomsIdGetOptions, getRomsApiRomsGetOptions } from "../clients/romm/@tanstack/react-query.gen"; import { getRomApiRomsIdGetOptions, getRomsApiRomsGetOptions } from "../clients/romm/@tanstack/react-query.gen";
import { GameListFilter } from "./components/GameList"; import { DefaultRommStaleTime, GameListFilterType } from "../shared/constants";
import { DefaultRommStaleTime } from "../shared/constants";
export function gamesQueryOptions (filter?: GameListFilter) export function gamesQueryOptions (filter?: GameListFilterType)
{ {
return queryOptions({ return queryOptions({
...getRomsApiRomsGetOptions({ query: { order_by: "updated_at", platform_ids: filter?.platformIds, collection_id: filter?.collectionId } }), ...getRomsApiRomsGetOptions({ query: { order_by: "updated_at", platform_ids: filter?.platform_id ? [filter?.platform_id] : null, collection_id: filter?.collection_id } }),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
placeholderData: keepPreviousData, placeholderData: keepPreviousData,
staleTime: DefaultRommStaleTime staleTime: DefaultRommStaleTime

View file

@ -1,10 +1,11 @@
import { createFileRoute } from '@tanstack/react-router'; import { createFileRoute } from '@tanstack/react-router';
import { CollectionsDetail } from '../components/CollectionsDetail'; import { CollectionsDetail } from '../components/CollectionsDetail';
import { getCollectionApiCollectionsIdGetOptions, getRomsApiRomsGetOptions } from '@clients/romm/@tanstack/react-query.gen'; import { getRomsApiRomsGetOptions } from '@clients/romm/@tanstack/react-query.gen';
import { DefaultRommStaleTime } from '@shared/constants'; import { DefaultRommStaleTime } from '@shared/constants';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useContext } from 'react'; import { useContext } from 'react';
import { AnimatedBackgroundContext } from '../scripts/contexts'; import { AnimatedBackgroundContext } from '../scripts/contexts';
import queries from '../scripts/queries';
export const Route = createFileRoute('/collection/$id')({ export const Route = createFileRoute('/collection/$id')({
component: RouteComponent, component: RouteComponent,
@ -17,7 +18,7 @@ export const Route = createFileRoute('/collection/$id')({
function RouteComponent () function RouteComponent ()
{ {
const { id } = Route.useParams(); const { id } = Route.useParams();
const { data: collection } = useQuery({ ...getCollectionApiCollectionsIdGetOptions({ path: { id: Number(id) } }) }); const { data: collection } = useQuery(queries.romm.getCollectionQuery(Number(id)));
const animatedBgContext = useContext(AnimatedBackgroundContext); const animatedBgContext = useContext(AnimatedBackgroundContext);
return ( return (

View file

@ -1,27 +1,26 @@
import { EMULATORJS_URL, RPC_URL, SERVER_URL } from '@/shared/constants'; import { RPC_URL, SERVER_URL } from '@/shared/constants';
import { createFileRoute } from '@tanstack/react-router'; import { createFileRoute } from '@tanstack/react-router';
import { gameQuery } from '../scripts/queries';
import { zodValidator } from '@tanstack/zod-adapter'; import { zodValidator } from '@tanstack/zod-adapter';
import z from 'zod'; import z from 'zod';
import { RefObject, useEffect, useRef, useState } from 'react'; import { RefObject, useEffect, useRef, useState } from 'react';
import { Router } from '..'; import { Router } from '..';
import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation'; import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { Button, ButtonStyle } from '../components/options/Button'; import { ButtonStyle } from '../components/options/Button';
import { DoorOpen, Home, RefreshCw, Undo } from 'lucide-react'; import { DoorOpen, RefreshCw, Undo } from 'lucide-react';
import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts'; import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts';
import Shortcuts from '../components/Shortcuts'; import Shortcuts from '../components/Shortcuts';
import { useEventListener, useTimeout } from 'usehooks-ts'; import { useEventListener } from 'usehooks-ts';
import { GetFocusedElement, useGlobalFocus } from '../scripts/spatialNavigation';
import useActiveControl from '../scripts/gamepads'; import useActiveControl from '../scripts/gamepads';
import { twMerge } from 'tailwind-merge'; import { twMerge } from 'tailwind-merge';
import { HeaderAccounts, HeaderStatusBar } from '../components/Header'; import { HeaderAccounts, HeaderStatusBar } from '../components/Header';
import { RoundButton } from '../components/RoundButton'; import { RoundButton } from '../components/RoundButton';
import queries from '../scripts/queries';
export const Route = createFileRoute('/embedded/$source/$id')({ export const Route = createFileRoute('/embedded/$source/$id')({
component: RouteComponent, component: RouteComponent,
loader: async (ctx) => loader: async (ctx) =>
{ {
const data = await ctx.context.queryClient.fetchQuery(gameQuery(ctx.params.source, ctx.params.id)); const data = await ctx.context.queryClient.fetchQuery(queries.romm.gameQuery(ctx.params.source, ctx.params.id));
return { data }; return { data };
}, },
validateSearch: zodValidator(z.record(z.string(), z.string().optional().nullable())) validateSearch: zodValidator(z.record(z.string(), z.string().optional().nullable()))

View file

@ -1,6 +1,6 @@
import { createFileRoute, ErrorComponentProps } from "@tanstack/react-router"; import { createFileRoute, ErrorComponentProps } from "@tanstack/react-router";
import { CommandEntry, FrontEndGameTypeDetailed, GameInstallProgress, GameStatusType, RPC_URL } from "@shared/constants"; import { CommandEntry, FrontEndGameTypeDetailed, GameInstallProgress, GameStatusType, RPC_URL } from "@shared/constants";
import { twJoin, twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { JSX, RefObject, useEffect, useRef, useState } from "react"; import { JSX, RefObject, useEffect, useRef, useState } from "react";
import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation"; import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames"; import classNames from "classnames";
@ -11,20 +11,20 @@ import { PopSource, SaveSource, useFocusEventListener } from "../../scripts/spat
import { AnimatedBackground } from "../../components/AnimatedBackground"; import { AnimatedBackground } from "../../components/AnimatedBackground";
import { rommApi } from "../../scripts/clientApi"; import { rommApi } from "../../scripts/clientApi";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Router } from "../.."; import { Router } from "../..";
import { ContextDialog, ContextList, DialogEntry } from "../../components/ContextDialog"; import { ContextDialog, ContextList, DialogEntry } from "../../components/ContextDialog";
import Shortcuts from "../../components/Shortcuts"; import Shortcuts from "../../components/Shortcuts";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "@/mainview/scripts/shortcuts"; import { GamePadButtonCode, useShortcutContext, useShortcuts } from "@/mainview/scripts/shortcuts";
import { gameQuery } from "@/mainview/scripts/queries"; import queries from "@/mainview/scripts/queries";
import Screenshots from "@/mainview/components/Screenshots"; import Screenshots from "@/mainview/components/Screenshots";
import { delay, useSticky, useStickyDataAttr } from "@/mainview/scripts/utils"; import { useStickyDataAttr } from "@/mainview/scripts/utils";
import useActiveControl from "@/mainview/scripts/gamepads"; import useActiveControl from "@/mainview/scripts/gamepads";
export const Route = createFileRoute("/game/$source/$id")({ export const Route = createFileRoute("/game/$source/$id")({
loader: async ({ params, context }) => loader: async ({ params, context }) =>
{ {
const data = await context.queryClient.fetchQuery(gameQuery(params.source, params.id)); const data = await context.queryClient.fetchQuery(queries.romm.gameQuery(params.source, params.id));
return { data }; return { data };
}, },
component: GameDetailsUI, component: GameDetailsUI,
@ -402,8 +402,7 @@ function ActionButtons (data: { game: FrontEndGameTypeDetailed; })
const { ref, focusKey } = useFocusable({ focusKey: 'actions', onBlur: () => setHoverText(undefined) }); const { ref, focusKey } = useFocusable({ focusKey: 'actions', onBlur: () => setHoverText(undefined) });
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const deleteMutation = useMutation({ const deleteMutation = useMutation({
mutationKey: ['delete', data.game.id], ...queries.romm.deleteGameMutation,
mutationFn: () => rommApi.api.romm.game({ source: data.game.id.source })({ id: data.game.id.id }).delete(),
onSuccess: () => onSuccess: () =>
{ {
location.reload(); location.reload();
@ -493,7 +492,7 @@ function ActionButton (data: {
disabled?: boolean; disabled?: boolean;
}) })
{ {
const { ref, focused } = useFocusable({ focusKey: data.id, onFocus: data.onFocus, onEnterPress: data.onAction, focusable: data.disabled !== true }); const { ref } = useFocusable({ focusKey: data.id, onFocus: data.onFocus, onEnterPress: data.onAction, focusable: data.disabled !== true });
const styles = { const styles = {
primary: "bg-primary text-primary-content focused:bg-base-content focused:text-base-300 focusable focusable-primary", primary: "bg-primary text-primary-content focused:bg-base-content focused:text-base-300 focusable focusable-primary",
base: " text-base-content border-dashed border-base-content/20 border-2 focused:bg-base-content focused:text-base-300 focusable focusable-primary", base: " text-base-content border-dashed border-base-content/20 border-2 focused:bg-base-content focused:text-base-300 focusable focusable-primary",

View file

@ -0,0 +1,21 @@
import { createFileRoute } from '@tanstack/react-router';
import { CollectionsDetail } from '../components/CollectionsDetail';
import { zodValidator } from '@tanstack/zod-adapter';
import z from 'zod';
export const Route = createFileRoute('/games')({
component: RouteComponent,
validateSearch: zodValidator(z.object({ focus: z.string().optional() }))
});
function RouteComponent ()
{
const { focus } = Route.useSearch();
return (
<div className="w-full h-full">
<CollectionsDetail focus={focus} id='all-games'
/>
</div>
);
}

View file

@ -1,4 +1,4 @@
import { JSX, Suspense, useContext, useState } from "react"; import { JSX, Suspense, useContext, useEffect, useState } from "react";
import import
{ {
Gamepad2, Gamepad2,
@ -21,7 +21,6 @@ import
{ {
FocusContext, FocusContext,
FocusDetails, FocusDetails,
getCurrentFocusKey,
useFocusable, useFocusable,
} from "@noriginmedia/norigin-spatial-navigation"; } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames"; import classNames from "classnames";
@ -38,7 +37,6 @@ import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import Shortcuts from "../components/Shortcuts"; import Shortcuts from "../components/Shortcuts";
import { PlatformsList } from "../components/PlatformsList"; import { PlatformsList } from "../components/PlatformsList";
import { systemApi } from "../scripts/clientApi";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "../scripts/shortcuts"; import { GamePadButtonCode, useShortcutContext, useShortcuts } from "../scripts/shortcuts";
import z from "zod"; import z from "zod";
import { Router } from ".."; import { Router } from "..";
@ -47,6 +45,8 @@ import { zodValidator } from '@tanstack/zod-adapter';
import { mobileCheck, useDragScroll } from "../scripts/utils"; import { mobileCheck, useDragScroll } from "../scripts/utils";
import { AnimatedBackgroundContext } from "../scripts/contexts"; import { AnimatedBackgroundContext } from "../scripts/contexts";
import { FrontEndId } from "@/shared/constants"; import { FrontEndId } from "@/shared/constants";
import Carousel from "../components/Carousel";
import queries from "../scripts/queries";
export const Route = createFileRoute("/")({ export const Route = createFileRoute("/")({
component: ConsoleHomeUI, component: ConsoleHomeUI,
@ -90,6 +90,16 @@ function HomeListError (data: { focused: boolean; })
</div></div>; </div></div>;
} }
function ShowAllGamesCard ()
{
const handleNavigate = () =>
{
Router.navigate({ to: '/games', viewTransition: { types: ['zoom-in'] } });
};
const { ref } = useFocusable({ focusKey: 'all-games-btn', onEnterPress: handleNavigate });
return <div ref={ref} onClick={handleNavigate} className="flex focusable focusable-primary justify-center items-center bg-base-300/80 rounded-3xl font-semibold w-(--game-card-width) h-(--game-card-height) focusable-hover cursor-pointer">All Games</div>;
}
function HomeList (data: { function HomeList (data: {
selectedFilter: string; selectedFilter: string;
}) })
@ -104,8 +114,8 @@ function HomeList (data: {
const handleNodeFocus = (id: string, node: HTMLElement, details: FocusDetails) => const handleNodeFocus = (id: string, node: HTMLElement, details: FocusDetails) =>
{ {
const isMounseEvent = details.nativeEvent instanceof MouseEvent; const isMouseEvent = details.nativeEvent instanceof MouseEvent;
if (!isMounseEvent) if (!isMouseEvent)
{ {
node?.scrollIntoView({ inline: 'center', block: 'center', behavior: initFocus ? 'smooth' : 'instant' }); node?.scrollIntoView({ inline: 'center', block: 'center', behavior: initFocus ? 'smooth' : 'instant' });
} }
@ -136,19 +146,29 @@ function HomeList (data: {
{ {
case 'consoles': case 'consoles':
activeList = <> activeList = <>
<PlatformsList onSelect={handlePlatformSelect} onFocus={handleNodeFocus} className="animate-slide-up" key="consoles-list" id="consoles-list" setBackground={bg.setBackground} /> <PlatformsList saveChildFocus="session" onSelect={handlePlatformSelect} onFocus={handleNodeFocus} className="animate-slide-up" key="consoles-list" id="consoles-list" setBackground={bg.setBackground} />
<AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} /> <AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} />
</>; </>;
break; break;
case 'collections': case 'collections':
activeList = <> activeList = <>
<CollectionList onSelect={handleCollectionSelect} onFocus={handleNodeFocus} className="animate-slide-up" key="collections-list" id="collections-list" setBackground={bg.setBackground} /> <CollectionList saveChildFocus="session" onSelect={handleCollectionSelect} onFocus={handleNodeFocus} className="animate-slide-up" key="collections-list" id="collections-list" setBackground={bg.setBackground} />
<AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} /> <AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} />
</>; </>;
break; break;
default: default:
activeList = <> activeList = <>
<GameList onGameSelect={handleGameSelect} onFocus={handleNodeFocus} className="animate-slide-up" key="games-list" id="games-list" setBackground={bg.setBackground} /> <GameList
onGameSelect={handleGameSelect}
saveChildFocus="session"
onFocus={handleNodeFocus}
className="animate-slide-up"
key="games-list"
id="games-list"
setBackground={bg.setBackground}
filters={{ limit: 12 }}
finalElement={<ShowAllGamesCard />}
/>
<AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} /> <AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} />
</>; </>;
break; break;
@ -182,7 +202,7 @@ function HomeList (data: {
return ( return (
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<div ref={ref} className="flex h-full w-full landscape:overflow-x-scroll portrait:overflow-y-scroll overflow-hidden no-scrollbar justify-center-safe sm:py-2 md:py-6 md:pb-6 md:mb-1 not-mobile:sm:pb-4" style={{ <Carousel scrollRef={ref} rootClassName="h-full w-full" className="flex h-full w-full landscape:overflow-x-scroll portrait:overflow-y-scroll overflow-hidden no-scrollbar justify-center-safe sm:py-2 md:py-6 md:pb-6 md:mb-1 not-mobile:sm:pb-4" style={{
mask: `linear-gradient(to right, rgba(0,0,0,0.8) 0%, black 10%, black 90%, rgba(0,0,0,0.8) 100%)` mask: `linear-gradient(to right, rgba(0,0,0,0.8) 0%, black 10%, black 90%, rgba(0,0,0,0.8) 100%)`
}}> }}>
<div className="landscape:flex landscape:px-16 portrait:min-h-fit portrait:h-fit portrait:pb-32 portrait:w-full landscape:h-full landscape:items-center"> <div className="landscape:flex landscape:px-16 portrait:min-h-fit portrait:h-fit portrait:pb-32 portrait:w-full landscape:h-full landscape:items-center">
@ -193,17 +213,16 @@ function HomeList (data: {
</Suspense> </Suspense>
</ErrorBoundary> </ErrorBoundary>
</div> </div>
</div> </Carousel>
</FocusContext> </FocusContext>
); );
} }
function MainMenu (data: {}) function MainMenu ()
{ {
const { ref, focusKey, hasFocusedChild } = useFocusable({ const { ref, focusKey } = useFocusable({
focusKey: `main-menu`, focusKey: `main-menu`,
trackChildren: true, trackChildren: true,
onBlur: (layout, props, details) => { },
}); });
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
@ -214,7 +233,7 @@ function MainMenu (data: {})
> >
<FocusContext.Provider value={focusKey}> <FocusContext.Provider value={focusKey}>
<CircleIcon <CircleIcon
action={() => navigate({ to: "/" })} action={() => navigate({ to: "/games", viewTransition: { types: ['zoom-in'] } })}
icon={<Gamepad2 />} icon={<Gamepad2 />}
label="Home" label="Home"
type="secondary" type="secondary"
@ -248,7 +267,7 @@ function CircleIcon (data: {
icon?: JSX.Element; icon?: JSX.Element;
}) })
{ {
const { ref, focused, focusKey } = useFocusable({ const { ref, focusKey } = useFocusable({
focusKey: `navigation-icon-${data.label}`, focusKey: `navigation-icon-${data.label}`,
onEnterPress: data.action, onEnterPress: data.action,
}); });
@ -275,15 +294,9 @@ export default function ConsoleHomeUI ()
{ {
const { filter } = Route.useSearch(); const { filter } = Route.useSearch();
const closeMutation = useMutation({ const close = useMutation(queries.system.closeMutation);
mutationKey: ['close'], mutationFn: async () =>
{
const { error } = await systemApi.api.system.exit.post();
if (error) throw error;
}
});
const { ref, focusKey, focusSelf } = useFocusable({ const { ref, focusKey } = useFocusable({
forceFocus: true, forceFocus: true,
autoRestoreFocus: false, autoRestoreFocus: false,
saveLastFocusedChild: false, saveLastFocusedChild: false,
@ -319,7 +332,7 @@ export default function ConsoleHomeUI ()
const headerButtons = []; const headerButtons = [];
if (mobileCheck()) if (mobileCheck())
headerButtons.push({ id: "fullscreen", icon: <Maximize />, action: handleFullscreen }); headerButtons.push({ id: "fullscreen", icon: <Maximize />, action: handleFullscreen });
headerButtons.push({ id: "search", icon: <Search /> }, { id: "power-button", icon: <Power />, external: true, action: () => closeMutation.mutate() }); headerButtons.push({ id: "search", icon: <Search /> }, { id: "power-button", icon: <Power />, external: true, action: () => close.mutate() });
return ( return (
<AnimatedBackground animated ref={ref} backgroundKey="home-background" className="grid grid-cols-3 sm:landscape:grid-rows-[3rem_minmax(var(--game-card-height-safe),1fr)_4rem] md:landscape:grid-rows-[5rem_4rem_minmax(var(--game-card-height-safe),1fr)_6rem_6rem] gap-1 portrait:grid-rows-[3rem_4rem_minmax(var(--game-card-height-safe),1fr)] max-h-screen overflow-clip"> <AnimatedBackground animated ref={ref} backgroundKey="home-background" className="grid grid-cols-3 sm:landscape:grid-rows-[3rem_minmax(var(--game-card-height-safe),1fr)_4rem] md:landscape:grid-rows-[5rem_4rem_minmax(var(--game-card-height-safe),1fr)_6rem_6rem] gap-1 portrait:grid-rows-[3rem_4rem_minmax(var(--game-card-height-safe),1fr)] max-h-screen overflow-clip">

View file

@ -4,11 +4,11 @@ import { GameInstallProgress, RPC_URL } from '@/shared/constants';
import DotsLoading from '../components/backgrounds/dots'; import DotsLoading from '../components/backgrounds/dots';
import { Router } from '..'; import { Router } from '..';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { rommApi } from '../scripts/clientApi';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts'; import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts';
import { useFocusable } from '@noriginmedia/norigin-spatial-navigation'; import { useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import Shortcuts from '../components/Shortcuts'; import Shortcuts from '../components/Shortcuts';
import queries from '../scripts/queries';
export const Route = createFileRoute('/launcher/$source/$id')({ export const Route = createFileRoute('/launcher/$source/$id')({
component: RouteComponent, component: RouteComponent,
@ -23,7 +23,7 @@ function RouteComponent ()
const { source, id } = Route.useParams(); const { source, id } = Route.useParams();
const { ref, focusKey } = useFocusable({ focusKey: `launching-${source}-${id}` }); const { ref, focusKey } = useFocusable({ focusKey: `launching-${source}-${id}` });
const { data } = useQuery({ queryKey: ['romm', 'game'], queryFn: () => rommApi.api.romm.game({ source })({ id }).get() }); const { data } = useQuery(queries.romm.gameQuery(source, id));
useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: HandleGoBack }]); useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: HandleGoBack }]);
const { shortcuts } = useShortcutContext(); const { shortcuts } = useShortcutContext();
@ -58,7 +58,7 @@ function RouteComponent ()
return <AnimatedBackground ref={ref} backgroundKey='game-details'> return <AnimatedBackground ref={ref} backgroundKey='game-details'>
<div className='flex shadow-2xs shadow-black flex-col absolute w-screen h-screen overflow-hidden justify-center items-center gap-4'> <div className='flex shadow-2xs shadow-black flex-col absolute w-screen h-screen overflow-hidden justify-center items-center gap-4'>
<DotsLoading /> <DotsLoading />
<h1 className='font-semibold'>Launching {data?.data?.name} ...</h1> <h1 className='font-semibold'>Launching {data?.name} ...</h1>
</div> </div>
<div className='absolute bot'> <div className='absolute bot'>
<Shortcuts shortcuts={shortcuts} /> <Shortcuts shortcuts={shortcuts} />

View file

@ -1,10 +1,8 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
import { CollectionsDetail } from "../components/CollectionsDetail"; import { CollectionsDetail } from "../components/CollectionsDetail";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { DefaultRommStaleTime, RPC_URL } from "../../shared/constants"; import { RPC_URL } from "../../shared/constants";
import { useContext } from "react"; import queries from "../scripts/queries";
import { rommApi } from "../scripts/clientApi";
import { AnimatedBackgroundContext } from "../scripts/contexts";
export const Route = createFileRoute("/platform/$source/$id")({ export const Route = createFileRoute("/platform/$source/$id")({
component: RouteComponent component: RouteComponent
@ -24,22 +22,12 @@ function PlatformTitle (data: { pathCover: string | null, platformName?: string;
function RouteComponent () function RouteComponent ()
{ {
const { source, id } = Route.useParams(); const { source, id } = Route.useParams();
const { data: platform } = useQuery({ const { data: platform } = useQuery(queries.romm.platformQuery(source, id));
queryKey: ['platform', source, id], queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.platforms({ source })({ id }).get();
if (error) throw error;
return data;
}, staleTime: DefaultRommStaleTime
});
const animatedBgContext = useContext(AnimatedBackgroundContext);
return ( return (
<div className="w-full h-full"> <div className="w-full h-full">
{!!platform && <CollectionsDetail {!!platform && <CollectionsDetail
title={<PlatformTitle pathCover={platform.path_cover} platformName={platform.name} />} title={<PlatformTitle pathCover={platform.path_cover} platformName={platform.name} />}
setBackground={animatedBgContext.setBackground}
filters={{ platform_id: Number(id), platform_slug: platform.slug, platform_source: source }} filters={{ platform_id: Number(id), platform_slug: platform.slug, platform_source: source }}
/>} />}
</div> </div>

View file

@ -1,4 +1,5 @@
import { systemApi } from '@/mainview/scripts/clientApi';
import queries from '@/mainview/scripts/queries';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router'; import { createFileRoute } from '@tanstack/react-router';
import prettyBytes from 'pretty-bytes'; import prettyBytes from 'pretty-bytes';
@ -9,7 +10,7 @@ export const Route = createFileRoute('/settings/about')({
function RouteComponent () function RouteComponent ()
{ {
const { data: systemInfo } = useQuery({ queryKey: ['system-info'], queryFn: () => systemApi.api.system.info.get() }); const { data: systemInfo } = useQuery(queries.system.systemInfoQuery);
return <table className="table"> return <table className="table">
<tbody> <tbody>
<tr> <tr>

View file

@ -13,23 +13,17 @@ import
useEffect, useEffect,
useRef, useRef,
} from "react"; } from "react";
import { RPC_URL } from "@shared/constants"; import { RommLoginDataSchema, RPC_URL } from "@shared/constants";
import
{
getCurrentUserApiUsersMeGetOptions,
statsApiStatsGetOptions,
} from "@clients/romm/@tanstack/react-query.gen";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import z from "zod";
import { OptionSpace } from "../../components/options/OptionSpace"; import { OptionSpace } from "../../components/options/OptionSpace";
import { useSettingsForm, useSettingsFormContext } from "../../components/options/SettingsAppForm"; import { useSettingsForm, useSettingsFormContext } from "../../components/options/SettingsAppForm";
import { rommApi, settingsApi } from "../../scripts/clientApi";
import { Button } from "../../components/options/Button"; import { Button } from "../../components/options/Button";
import { ContextDialog } from "@/mainview/components/ContextDialog"; import { ContextDialog } from "@/mainview/components/ContextDialog";
import QRCode from "react-qr-code"; import QRCode from "react-qr-code";
import { useJobStatus } from "@/mainview/scripts/utils"; import { useJobStatus } from "@/mainview/scripts/utils";
import { useInterval } from "usehooks-ts"; import { useInterval } from "usehooks-ts";
import { TwitchIcon } from "@/mainview/scripts/brandIcons"; import { TwitchIcon } from "@/mainview/scripts/brandIcons";
import queries from "@/mainview/scripts/queries";
export const Route = createFileRoute("/settings/accounts")({ export const Route = createFileRoute("/settings/accounts")({
component: RouteComponent, component: RouteComponent,
@ -56,44 +50,16 @@ function LoginQR (data: { id: string, isOpen: boolean, cancel: () => void, url:
</ContextDialog>; </ContextDialog>;
} }
function TwitchLogin (data: {}) function TwitchLogin ()
{ {
const loginStatus = useQuery(queries.settings.twitchLoginVerificationQuery);
const loginStatus = useQuery({
queryKey: ['twitch', 'login', 'status'],
retry (failureCount, error)
{
if (error.status === 404)
{
return false;
}
return failureCount < 3;
},
queryFn: async () =>
{
const { data, error, status } = await rommApi.api.romm.login.twitch.get();
if (error) throw { ...error, status };
return data;
}
});
const loginMutation = useMutation({ const loginMutation = useMutation({
mutationKey: ['twitch', 'login'], ...queries.settings.twitchLoginMutation,
mutationFn: (openInBrowser: boolean) =>
{
return rommApi.api.romm.login.twitch.post({ openInBrowser });
},
onSuccess: () => loginStatus.refetch() onSuccess: () => loginStatus.refetch()
}); });
const logoutMutation = useMutation({ const logoutMutation = useMutation({ ...queries.settings.twitchLogoutMutation, onSuccess: () => loginStatus.refetch() });
mutationKey: ['twitch', 'logout'],
mutationFn: () =>
{
return rommApi.api.romm.logout.twitch.post();
},
onSuccess: () => loginStatus.refetch()
});
const { data: loginData, wsRef } = useJobStatus('twitch-login-job', { onEnded: () => loginStatus.refetch() }); const { data: loginData, wsRef } = useJobStatus('twitch-login-job', { onEnded: () => loginStatus.refetch() });
@ -118,22 +84,13 @@ function TwitchLogin (data: {})
function LoginControls (data: { hasPassword: boolean; }) function LoginControls (data: { hasPassword: boolean; })
{ {
const user = useQuery({ const user = useQuery(queries.romm.rommUserQuery());
...getCurrentUserApiUsersMeGetOptions(), const loginMutation = useMutation(queries.romm.rommQrLoginMutation);
queryKey: ['romm', 'auth', "login"], const { data: statusValue, wsRef } = useJobStatus('login-job');
refetchOnWindowFocus: false,
retry: 0
});
const loginMutation = useMutation({
mutationKey: ['login', 'qr', 'cancel'],
mutationFn: () => rommApi.api.romm.login.romm.post()
});
const { data: statusValue, error: loginError, wsRef } = useJobStatus('login-job');
const context = useSettingsFormContext({}); const context = useSettingsFormContext({});
const isMutatingRomm = useIsMutating({ mutationKey: ["romm", "auth"] }) > 0; const isMutatingRomm = useIsMutating({ mutationKey: ["romm", "auth"] }) > 0;
const logoutMutation = useMutation({ const logoutMutation = useMutation({
mutationKey: ["romm", "auth", "logout"], mutationFn: () => rommApi.api.romm.logout.post(), ...queries.romm.rommLogoutMutation,
onSuccess: async (d, v, r, c) => onSuccess: async (d, v, r, c) =>
{ {
user.refetch(); user.refetch();
@ -171,8 +128,6 @@ function LoginControls (data: { hasPassword: boolean; })
</div>; </div>;
} }
const dataSchema = z.object({ hostname: z.url(), username: z.string(), password: z.string() });
function RouteComponent () function RouteComponent ()
{ {
const { focus } = Route.useSearch(); const { focus } = Route.useSearch();
@ -181,9 +136,9 @@ function RouteComponent ()
preferredChildFocusKey: focus preferredChildFocusKey: focus
}); });
const { data: hasPassword } = useQuery({ queryKey: ['romm', 'auth', 'passLength'], queryFn: () => rommApi.api.romm.login.get().then(d => d.data?.hasPassword as boolean) }); const { data: hasPassword } = useQuery(queries.romm.rommHasPasswordQuery);
const { data: hostname } = useQuery({ queryKey: ['romm', 'auth', 'hostname'], queryFn: () => settingsApi.api.settings({ id: 'rommAddress' }).get().then(d => d.data?.value as string) }); const { data: hostname } = useQuery(queries.romm.rommHostnameQuery);
const { data: username } = useQuery({ queryKey: ['romm', 'auth', 'username'], queryFn: () => settingsApi.api.settings({ id: 'rommUser' }).get().then(d => d.data?.value as string) }); const { data: username } = useQuery(queries.romm.rommUsernameQuery);
const loginForm = useSettingsForm({ const loginForm = useSettingsForm({
defaultValues: { defaultValues: {
@ -201,15 +156,11 @@ function RouteComponent ()
loginForm.reset(); loginForm.reset();
}, },
validators: { validators: {
onChange: dataSchema onChange: RommLoginDataSchema
} }
}); });
const rommOnline = useQuery({ const rommOnline = useQuery(queries.romm.rommGetOptionsQuery());
...statsApiStatsGetOptions(),
refetchInterval: 30000,
retry: false,
});
useEffect(() => useEffect(() =>
{ {
@ -219,22 +170,7 @@ function RouteComponent ()
} }
}, [focus]); }, [focus]);
const loginMutation = useMutation({ const loginMutation = useMutation(queries.romm.rommLoginMutation);
mutationKey: ["romm", "login"],
mutationFn: async (data: z.infer<typeof dataSchema>) =>
{
const { error } = await rommApi.api.romm.login.post({ username: data.username, password: data.password, host: data.hostname });
if (error) throw error;
},
onSuccess: (d, v, r, c) =>
{
c.client.invalidateQueries({ queryKey: ['romm', 'auth'] });
},
onError: (e) =>
{
console.error(e);
},
});
let indicator = ""; let indicator = "";
if (rommOnline.isError) if (rommOnline.isError)

View file

@ -2,7 +2,7 @@ import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-naviga
import { Block, createFileRoute } from '@tanstack/react-router'; import { Block, createFileRoute } from '@tanstack/react-router';
import DownloadDirectoryOption from '@/mainview/components/options/DownloadDirectoryOption'; import DownloadDirectoryOption from '@/mainview/components/options/DownloadDirectoryOption';
import { useIsMutating, useMutation, useQuery } from '@tanstack/react-query'; import { useIsMutating, useMutation, useQuery } from '@tanstack/react-query';
import { changeDownloadsMutation, downloadDrivesQuery } from '@/mainview/scripts/queries'; import queries from '@/mainview/scripts/queries';
import { DownloadsDrive } from '@/shared/constants'; import { DownloadsDrive } from '@/shared/constants';
import prettyBytes from 'pretty-bytes'; import prettyBytes from 'pretty-bytes';
import classNames from 'classnames'; import classNames from 'classnames';
@ -24,11 +24,11 @@ function DriveComponent (data: { drive: DownloadsDrive; downloadsSize: number; r
focusKey: data.drive.device, focusKey: data.drive.device,
onFocus: () => (ref.current as HTMLElement)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) onFocus: () => (ref.current as HTMLElement)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}); });
const isMoving = useIsMutating(changeDownloadsMutation); const isMoving = useIsMutating(queries.settings.changeDownloadsMutation);
const usedWithoutDownlods = data.drive.used - (data.drive.isCurrentlyUsed ? data.downloadsSize : 0); const usedWithoutDownlods = data.drive.used - (data.drive.isCurrentlyUsed ? data.downloadsSize : 0);
const usedPercent = usedWithoutDownlods / data.drive.size; const usedPercent = usedWithoutDownlods / data.drive.size;
const usedPercentRaw = data.drive.used / data.drive.size; const usedPercentRaw = data.drive.used / data.drive.size;
const changeDownloads = useMutation({ ...changeDownloadsMutation, onSuccess: data.refetchDrives }); data.drive.unusableReason; const changeDownloads = useMutation({ ...queries.settings.changeDownloadsMutation, onSuccess: data.refetchDrives }); data.drive.unusableReason;
const shortcuts: Shortcut[] = []; const shortcuts: Shortcut[] = [];
const valid = !data.drive.unusableReason && isMoving <= 0; const valid = !data.drive.unusableReason && isMoving <= 0;
const handleAction = () => changeDownloads.mutate(data.drive.mountPoint); const handleAction = () => changeDownloads.mutate(data.drive.mountPoint);
@ -74,16 +74,16 @@ function DriveComponent (data: { drive: DownloadsDrive; downloadsSize: number; r
function RouteComponent () function RouteComponent ()
{ {
const { focus } = Route.useSearch(); const { focus } = Route.useSearch();
const { ref, focusKey, focusSelf } = useFocusable({ const { ref, focusKey } = useFocusable({
focusKey: "directories", focusKey: "directories",
preferredChildFocusKey: focus preferredChildFocusKey: focus
}); });
const isMoving = useIsMutating(changeDownloadsMutation); const isMoving = useIsMutating(queries.settings.changeDownloadsMutation);
const { data: drives, refetch } = useQuery({ ...downloadDrivesQuery, refetchInterval: isMoving > 0 ? 1000 : undefined }); const { data: drives, refetch } = useQuery({ ...queries.system.downloadDrivesQuery, refetchInterval: isMoving > 0 ? 1000 : undefined });
return <FocusContext value={focusKey}> return <FocusContext value={focusKey}>
<Block shouldBlockFn={() => isMoving} withResolver={false} /> <Block shouldBlockFn={() => isMoving > 0} withResolver={false} />
<ul ref={ref} className="list rounded-box gap-2"> <ul ref={ref} className="list rounded-box gap-2">
<div className="divider text-2xl mt-0 md:mt-4"> <div className="divider text-2xl mt-0 md:mt-4">
<Download className='size-16' /> Downloads ({drives?.downloadsSize ? prettyBytes(drives?.downloadsSize) : <span className="loading loading-spinner loading-lg size-6"></span>}) <Download className='size-16' /> Downloads ({drives?.downloadsSize ? prettyBytes(drives?.downloadsSize) : <span className="loading loading-spinner loading-lg size-6"></span>})

View file

@ -2,7 +2,6 @@ import { createFileRoute } from '@tanstack/react-router';
import { OptionSpace } from '../../components/options/OptionSpace'; import { OptionSpace } from '../../components/options/OptionSpace';
import { OptionInput } from '../../components/options/OptionInput'; import { OptionInput } from '../../components/options/OptionInput';
import { useMutation, useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { settingsApi } from '../../scripts/clientApi';
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { Button } from '../../components/options/Button'; import { Button } from '../../components/options/Button';
import { Check, ChevronDown, FolderSearch, SearchAlert, Trash, TriangleAlert } from 'lucide-react'; import { Check, ChevronDown, FolderSearch, SearchAlert, Trash, TriangleAlert } from 'lucide-react';
@ -15,7 +14,7 @@ import { FocusContext, setFocus, useFocusable } from '@noriginmedia/norigin-spat
import { GamePadButtonCode, useShortcuts } from '@/mainview/scripts/shortcuts'; import { GamePadButtonCode, useShortcuts } from '@/mainview/scripts/shortcuts';
import FilePicker from '@/mainview/components/FilePicker'; import FilePicker from '@/mainview/components/FilePicker';
import { dirname } from 'pathe'; import { dirname } from 'pathe';
import { autoEmulatorsQuery } from '@/mainview/scripts/queries'; import queries from '@/mainview/scripts/queries';
export const Route = createFileRoute('/settings/emulators')({ export const Route = createFileRoute('/settings/emulators')({
component: RouteComponent, component: RouteComponent,
@ -33,7 +32,7 @@ function EmulatorsPending ()
function EmulatorListCat (data: { selected: string, set: (c: string) => void; }) function EmulatorListCat (data: { selected: string, set: (c: string) => void; })
{ {
const { ref, focused, focusKey } = useFocusable({ focusKey: 'categories' }); const { ref, focusKey } = useFocusable({ focusKey: 'categories' });
return <ul className='flex gap-1' ref={ref}> return <ul className='flex gap-1' ref={ref}>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
{[..."ABCDEFGHIJKLMNOPQRSTVWXYZ"].map(c => {[..."ABCDEFGHIJKLMNOPQRSTVWXYZ"].map(c =>
@ -99,40 +98,13 @@ function EmulatorPath (data: { id: string; })
const [isSearching, setIsSearching] = useState(false); const [isSearching, setIsSearching] = useState(false);
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const [localValue, setLocalValue] = useState<string | undefined>(); const [localValue, setLocalValue] = useState<string | undefined>();
const { data: remoteValue } = useQuery({ const { data: remoteValue } = useQuery(queries.settings.customEmulatorRemoveValueQuery(data.id));
enabled: !!data.id, const setSettingMutation = useMutation(queries.settings.setCustomEmulatorMutation(data.id, (v) =>
queryKey: ["emulator", data.id], {
queryFn: async () => setLocalValue(v);
{ setDirty(false);
const { data: value, error } = await settingsApi.api.settings.emulators.custom({ id: data.id }).get(); }));
if (error) throw error; const deleteMutation = useMutation(queries.settings.customEmulatorDeleteMutation(data.id));
return value;
},
});
const setSettingMutation = useMutation({
mutationKey: ["emulator", data.id, 'set'],
mutationFn: async (value: string) => settingsApi.api.settings.emulators.custom({ id: data.id }).put({ value }),
onSuccess: (d, v, r, ctx) =>
{
ctx.client.invalidateQueries({ queryKey: ["emulator", data.id] });
ctx.client.invalidateQueries({ queryKey: ["auto-emulators"] });
setLocalValue(v);
setDirty(false);
}
});
const deleteMutation = useMutation({
mutationKey: ["emulator", data.id, 'delete'],
mutationFn: async () =>
{
const { error } = await settingsApi.api.settings.emulators.custom({ id: data.id }).delete();
if (error) throw error;
},
onSuccess: (d, v, r, ctx) =>
{
ctx.client.invalidateQueries({ queryKey: ['custom-emulators'] });
ctx.client.invalidateQueries({ queryKey: ["auto-emulators"] });
}
});
const handleSave = useCallback(() => const handleSave = useCallback(() =>
{ {
@ -251,11 +223,11 @@ function EmulatorBadge (data: {
function EmulatorBadges (data: { path?: string; addOverride: (emulator: string) => void; }) function EmulatorBadges (data: { path?: string; addOverride: (emulator: string) => void; })
{ {
const { data: autoEmulators } = useQuery(autoEmulatorsQuery); const { data: autoEmulators } = useQuery(queries.settings.autoEmulatorsQuery);
const { ref, focusKey } = useFocusable({ focusKey: `emulator-badges`, focusable: !!autoEmulators && autoEmulators.length > 0 }); const { ref, focusKey } = useFocusable({ focusKey: `emulator-badges`, focusable: !!autoEmulators && autoEmulators.length > 0 });
return <div ref={ref} className='grid grid-cols-[repeat(auto-fit,14rem)] auto-rows-[4rem] gap-2 justify-center-safe'> return <div ref={ref} className='grid grid-cols-[repeat(auto-fit,14rem)] auto-rows-[4rem] gap-2 justify-center-safe'>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
{autoEmulators?.map(e => <EmulatorBadge key={e.emulator} isCritical={e.isCritical} addOverride={data.addOverride} pathCover={e.path_cover ?? undefined} path={e.path?.path} exists={e.exists} emulator={e.emulator} />)} {autoEmulators?.map(e => <EmulatorBadge key={e.name} isCritical={e.isCritical} addOverride={data.addOverride} pathCover={e.logo} path={e.path?.path} exists={e.exists} emulator={e.name} />)}
</FocusContext> </FocusContext>
</div>; </div>;
} }
@ -263,30 +235,14 @@ function EmulatorBadges (data: { path?: string; addOverride: (emulator: string)
function RouteComponent () function RouteComponent ()
{ {
const { focus } = Route.useSearch(); const { focus } = Route.useSearch();
const { ref, focusKey, focusSelf } = useFocusable({ const { ref, focusKey } = useFocusable({
focusKey: "emulators-setting", focusKey: "emulators-setting",
preferredChildFocusKey: focus preferredChildFocusKey: focus
}); });
const { data: customEmulators } = useQuery({ const { data: customEmulators } = useQuery(queries.settings.customEmulatorsQuery);
queryKey: ['custom-emulators'], queryFn: async () =>
{
const { data, error } = await settingsApi.api.settings.emulators.custom.get();
if (error) throw error;
return data;
}
});
const addOverrideMutation = useMutation({ const addOverrideMutation = useMutation(queries.settings.customEmulatorAddMutation);
mutationKey: ['emulator', 'custom', 'add'],
mutationFn: async (id: string) =>
{
const { data, error } = await settingsApi.api.settings.emulators.custom({ id }).put({ value: '' });
if (error) throw error;
return data;
},
onSuccess: (d, v, r, ctx) => ctx.client.invalidateQueries({ queryKey: ['custom-emulators'] })
});
return <FocusContext value={focusKey}> return <FocusContext value={focusKey}>
<ul ref={ref} className="list rounded-box gap-2"> <ul ref={ref} className="list rounded-box gap-2">

View file

@ -9,7 +9,7 @@ export const Route = createFileRoute('/settings/interface')({
function RouteComponent () function RouteComponent ()
{ {
const { focus } = Route.useSearch(); const { focus } = Route.useSearch();
const { ref, focusKey, focusSelf } = useFocusable({ const { ref, focusKey } = useFocusable({
focusKey: "interface-settings", focusKey: "interface-settings",
preferredChildFocusKey: focus preferredChildFocusKey: focus
}); });

View file

@ -55,7 +55,7 @@ function MenuItem (data: {
const { to, search } = PopSource('settings'); const { to, search } = PopSource('settings');
navigate({ to: data.return ? to ?? data.route : data.route, viewTransition: data.viewTransition, search: data.return ? search : undefined }); navigate({ to: data.return ? to ?? data.route : data.route, viewTransition: data.viewTransition, search: data.return ? search : undefined });
}; };
const { ref, focusSelf, focused } = useFocusable({ const { ref, focusSelf } = useFocusable({
focusKey: `menu-item-${data.route}`, focusKey: `menu-item-${data.route}`,
forceFocus: !!acitve, forceFocus: !!acitve,
onFocus: () => onFocus: () =>

View file

@ -12,7 +12,7 @@ import Shortcuts from "@/mainview/components/Shortcuts";
import { AnimatedBackground } from "@/mainview/components/AnimatedBackground"; import { AnimatedBackground } from "@/mainview/components/AnimatedBackground";
import { PopSource } from "@/mainview/scripts/spatialNavigation"; import { PopSource } from "@/mainview/scripts/spatialNavigation";
import { systemApi } from "@/mainview/scripts/clientApi"; import { systemApi } from "@/mainview/scripts/clientApi";
import { storeEmulatorDetailsQuery, storeEmulatorsRecommendedQuery } from "@/mainview/scripts/queries"; import queries from "@/mainview/scripts/queries";
import { Button } from "@/mainview/components/options/Button"; import { Button } from "@/mainview/components/options/Button";
import { ChevronDown, Download, Info, Settings } from "lucide-react"; import { ChevronDown, Download, Info, Settings } from "lucide-react";
import { ContextDialog, ContextList, DialogEntry } from "@/mainview/components/ContextDialog"; import { ContextDialog, ContextList, DialogEntry } from "@/mainview/components/ContextDialog";
@ -27,7 +27,7 @@ export const Route = createFileRoute('/store/details/emulator/$id')({
component: RouteComponent, component: RouteComponent,
async loader (ctx) async loader (ctx)
{ {
const emulator = await ctx.context.queryClient.fetchQuery(storeEmulatorDetailsQuery(ctx.params.id)); const emulator = await ctx.context.queryClient.fetchQuery(queries.store.storeEmulatorDetailsQuery(ctx.params.id));
return { emulator }; return { emulator };
} }
}); });
@ -107,7 +107,7 @@ export function RouteComponent ()
}); });
const { emulator } = Route.useLoaderData(); const { emulator } = Route.useLoaderData();
const { data: recommended } = useQuery(storeEmulatorsRecommendedQuery); const { data: recommended } = useQuery(queries.store.storeEmulatorsRecommendedQuery);
useShortcuts(focusKey, () => [{ useShortcuts(focusKey, () => [{
label: "Return", label: "Return",
@ -180,13 +180,7 @@ export function RouteComponent ()
setFocus("title-area"); setFocus("title-area");
Router.navigate({ to: '/store/details/emulator/$id', params: { id }, viewTransition: { types: ['zoom-in'] } }); Router.navigate({ to: '/store/details/emulator/$id', params: { id }, viewTransition: { types: ['zoom-in'] } });
}} }}
emulators={recommended.map(em => ({ emulators={recommended} />}
name: em.name,
id: em.name,
installed: em.exists,
logo: em.logo,
systems: em.systems
} satisfies ShopFrontEndEmulator))} />}
</div> </div>
</div> </div>
<div className='flex fixed bottom-4 left-4 right-4 justify-end z-10'> <div className='flex fixed bottom-4 left-4 right-4 justify-end z-10'>

View file

@ -1,5 +1,5 @@
import { storeEmulatorsQuery } from '@/mainview/scripts/queries';
import { createFileRoute, useSearch } from '@tanstack/react-router'; import { createFileRoute, useSearch } from '@tanstack/react-router';
import { Joystick } from 'lucide-react'; import { Joystick } from 'lucide-react';
import { useContext, useEffect } from 'react'; import { useContext, useEffect } from 'react';
@ -7,33 +7,13 @@ import { FocusContext, getCurrentFocusKey, useFocusable } from '@noriginmedia/no
import { StoreEmulatorCard } from '@/mainview/components/store/StoreEmulatorCard'; import { StoreEmulatorCard } from '@/mainview/components/store/StoreEmulatorCard';
import { StoreContext } from '@/mainview/scripts/contexts'; import { StoreContext } from '@/mainview/scripts/contexts';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation'; import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { useQuery } from '@tanstack/react-query';
import queries from '@/mainview/scripts/queries';
export const Route = createFileRoute('/store/tab/emulators')({ export const Route = createFileRoute('/store/tab/emulators')({
component: RouteComponent, component: RouteComponent,
pendingComponent: PendingComponent,
async loader ({ context })
{
const emulators = await context.queryClient.fetchQuery(storeEmulatorsQuery);
return { emulators };
},
}); });
function PendingComponent ()
{
return <section className="px-6 py-4">
<div className="divider text-info">
<Joystick className='size-12' />
<h2 className="font-bold uppercase tracking-widest">
Emulators
</h2>
</div>
{/* Cards */}
<div className="grid grid-cols-[repeat(auto-fill,18rem)] auto-rows-[12rem] py-2 px-4 gap-4 justify-center-safe">
{[1, 2, 3, 4, 5, 6].map(i => <div key={i} className="skeleton h-36 rounded-2xl" />)}
</div>
</section>;
}
function RouteComponent () function RouteComponent ()
{ {
const { focus } = useSearch({ from: '/store/tab' }); const { focus } = useSearch({ from: '/store/tab' });
@ -42,7 +22,7 @@ function RouteComponent ()
preferredChildFocusKey: focus preferredChildFocusKey: focus
}); });
const storeContext = useContext(StoreContext); const storeContext = useContext(StoreContext);
const { emulators } = Route.useLoaderData(); const { data: emulators } = useQuery(queries.store.storeEmulatorsQuery);
useEffect(() => useEffect(() =>
{ {
@ -64,7 +44,7 @@ function RouteComponent ()
</div> </div>
{/* Cards */} {/* Cards */}
<div className="grid grid-cols-[repeat(auto-fill,18rem)] auto-rows-[12rem] py-2 md:px-4 gap-4 justify-center-safe"> <div className="grid grid-cols-[repeat(auto-fill,18rem)] auto-rows-[12rem] py-2 md:px-4 gap-4 justify-center-safe">
{emulators && emulators.map((data) => ( {emulators?.map((data) => (
<StoreEmulatorCard <StoreEmulatorCard
id={data.name} id={data.name}
key={data.name} key={data.name}
@ -72,7 +52,7 @@ function RouteComponent ()
onFocus={({ node, details }) => { node.scrollIntoView({ behavior: details.instant ? 'instant' : 'smooth', block: 'center' }); }} onFocus={({ node, details }) => { node.scrollIntoView({ behavior: details.instant ? 'instant' : 'smooth', block: 'center' }); }}
onSelect={(id, focus) => storeContext.showDetails('emulator', 'store', id, focus)} onSelect={(id, focus) => storeContext.showDetails('emulator', 'store', id, focus)}
/> />
))} )) ?? Array.from({ length: 10 }).map((_, i) => <div key={i} className="skeleton rounded-3xl" />)}
</div> </div>
</FocusContext> </FocusContext>
</section> </section>

View file

@ -1,95 +1,23 @@
import { StoreGameCard } from '@/mainview/components/store/GamesSection'; import { FocusContext, getCurrentFocusKey, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { FocusContext, getCurrentFocusKey, setFocus, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { createFileRoute, useSearch } from '@tanstack/react-router'; import { createFileRoute, useSearch } from '@tanstack/react-router';
import { Gamepad, Gamepad2, HardDrive, Save } from 'lucide-react'; import { Gamepad2 } from 'lucide-react';
import { JSX, useContext, useEffect, useRef, useState } from 'react'; import { useEffect } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { StoreContext } from '@/mainview/scripts/contexts';
import { basename, dirname, extname } from 'pathe';
import { rommApi } from '@/mainview/scripts/clientApi';
import { FrontEndGameType, RPC_URL } from '@/shared/constants';
import CardElement from '@/mainview/components/CardElement';
import { FOCUS_KEYS } from '@/mainview/scripts/types';
import FrontEndGameCard from '@/mainview/components/FrontEndGameCard'; import FrontEndGameCard from '@/mainview/components/FrontEndGameCard';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation'; import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { useIntersectionObserver } from 'usehooks-ts'; import LoadMoreButton from '@/mainview/components/LoadMoreButton';
import queries from '@/mainview/scripts/queries';
const staleTime = 24 * 60 * 60 * 1000;
export const Route = createFileRoute('/store/tab/games')({ export const Route = createFileRoute('/store/tab/games')({
component: RouteComponent, component: RouteComponent
async loader (ctx)
{
/*const gamesManifest = await ctx.context.queryClient.fetchQuery({
queryKey: ['store-games-manifest'], queryFn: async () =>
{
const store = await fetch('https://api.github.com/repos/dragoonDorise/EmuDeck/git/trees/50261b66d69c1758efa28c6d7c54e45259a0c9c5?recursive=true').then(r => r.json());
return store.tree.filter((e: any) =>
{
if (e.type === 'blob' && e.path !== "featured.json")
{
return true;
}
return false;
}) as [];
}, staleTime
});
return { gamesManifest };*/
},
}); });
function LoadMoreButton (data: { isFetching: boolean; lastId?: string; } & FocusParams & InteractParams)
{
const handleAction = (e?: Event) =>
{
data.onAction?.(e);
if (data.lastId && focused)
setFocus(FOCUS_KEYS.GAME_CARD(data.lastId));
};
const { ref, focusKey, focused } = useFocusable({
focusKey: 'load-more-btn',
onFocus: (_l, _p, details) => data.onFocus?.(focusKey, ref.current, details),
onEnterPress: handleAction
});
const { ref: intersct } = useIntersectionObserver({
onChange: (isIntersecting, entry) =>
{
if (isIntersecting)
{
handleAction();
}
}
});
return <div ref={(r) =>
{
ref.current = r;
intersct(r);
}} className='flex bg-base-100 game-card focusable focusable-accent focusable-hover text-2xl justify-center items-center cursor-pointer' onClick={handleAction} id='load-more-btn'>{data.isFetching ? <span className="loading loading-spinner loading-xl"></span> : "Load More"}</div>;
}
function RouteComponent () function RouteComponent ()
{ {
const { focus } = useSearch({ from: '/store/tab' }); const { focus } = useSearch({ from: '/store/tab' });
const { ref, focusKey, focusSelf } = useFocusable({ focusKey: "main-area", preferredChildFocusKey: focus }); const { ref, focusKey, focusSelf } = useFocusable({ focusKey: "main-area", preferredChildFocusKey: focus });
const { data, fetchNextPage, isFetchingNextPage } = useInfiniteQuery<{ data: FrontEndGameType[], nextPage: number; }>({ const { data, fetchNextPage, isFetchingNextPage, isFetching } = useInfiniteQuery(queries.store.storeGamesInfiniteQuery);
initialPageParam: 0,
queryKey: ['store-games'],
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
queryFn: async (data) =>
{
const pageParam = data.pageParam as number;
const { data: games, error } = await rommApi.api.romm.games.get({ query: { source: 'store', offset: pageParam * 10, limit: 10 } });
if (error) throw error;
return { data: games.games, nextPage: pageParam + 1 };
}
});
useEffect(() => useEffect(() =>
{ {
@ -115,17 +43,21 @@ function RouteComponent ()
Games Games
</h2> </h2>
</div> </div>
<div className="grid grid-cols-[repeat(auto-fill,18rem)] auto-rows-[minmax(18rem,min-content)] py-2 md:px-4 gap-4 justify-center-safe"> <div className="grid grid-cols-[repeat(auto-fill,18rem)] auto-rows-[21rem] py-2 md:px-4 gap-4 justify-center-safe">
{data?.pages.flatMap((page) => ( {data?.pages.flatMap((page) => (
page.data.map((g, i) => <FrontEndGameCard onFocus={handleFocus} key={g.id.id} game={g} index={i} />)) page.data.map((g, i) => <FrontEndGameCard onFocus={handleFocus} key={g.id.id} game={g} index={i} />))
)} ) ?? Array.from({ length: 20 }).map((_, i) => <div key={i} className="flex flex-col gap-4">
<div className="skeleton grow w-full"></div>
<div className="skeleton h-4 w-[80%]"></div>
<div className="skeleton h-4 w-[40%]"></div>
</div>)}
<LoadMoreButton <LoadMoreButton
lastId={data?.pages.at(-1)?.data.at(-1)?.id.id} lastId={data?.pages.at(-1)?.data.at(-1)?.id.id}
onFocus={handleFocus} onFocus={handleFocus}
isFetching={isFetchingNextPage} isFetching={isFetchingNextPage || isFetching}
onAction={() => onAction={() =>
{ {
if (isFetchingNextPage) if (isFetchingNextPage || isFetching)
return; return;
fetchNextPage(); fetchNextPage();
}} /> }} />

View file

@ -1,11 +1,11 @@
import { createFileRoute, ErrorComponentProps, useSearch } from '@tanstack/react-router'; import { createFileRoute, useSearch } from '@tanstack/react-router';
import { useFocusable, FocusContext, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation"; import { useFocusable, FocusContext, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { MissingEmulatorsSection } from "../../../components/store/MissingEmulatorsSection"; import { MissingEmulatorsSection } from "../../../components/store/MissingEmulatorsSection";
import { EmulatorsSection } from "../../../components/store/EmulatorsSection"; import { EmulatorsSection } from "../../../components/store/EmulatorsSection";
import { GamesSection } from "../../../components/store/GamesSection"; import { GamesSection } from "../../../components/store/GamesSection";
import { StatsSection } from "../../../components/store/StatsSection"; import { StatsSection } from "../../../components/store/StatsSection";
import { FrontEndGameTypeDetailed, RPC_URL } from '@/shared/constants'; import { FrontEndGameTypeDetailed, RPC_URL } from '@/shared/constants';
import { autoEmulatorsQuery, storeEmulatorsRecommendedQuery, storeFeaturedGamesQuery } from '@/mainview/scripts/queries'; import queries from '@/mainview/scripts/queries';
import { useContext, useEffect, useRef, useState } from 'react'; import { useContext, useEffect, useRef, useState } from 'react';
import { scrollIntoViewHandler } from '@/mainview/scripts/utils'; import { scrollIntoViewHandler } from '@/mainview/scripts/utils';
import { StoreContext } from '@/mainview/scripts/contexts'; import { StoreContext } from '@/mainview/scripts/contexts';
@ -13,66 +13,34 @@ import { useInterval } from 'usehooks-ts';
import { Button } from '@/mainview/components/options/Button'; import { Button } from '@/mainview/components/options/Button';
import { HardDrive, Search } from 'lucide-react'; import { HardDrive, Search } from 'lucide-react';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation'; import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { useQuery } from '@tanstack/react-query';
export const Route = createFileRoute('/store/tab/')({ export const Route = createFileRoute('/store/tab/')({
component: RouteComponent, component: RouteComponent
pendingComponent: LoadingSkeleton,
errorComponent: ErrorComponent,
loader: async ({ context }) =>
{
const autoEmulators = await context.queryClient.fetchQuery(autoEmulatorsQuery);
const crutialEmulators = autoEmulators?.filter(e => !e.exists && e.isCritical);
const featuredGames = await await context.queryClient.fetchQuery(storeFeaturedGamesQuery);
const recommendedEmulators = await context.queryClient.fetchQuery(storeEmulatorsRecommendedQuery);
return { crutialEmulators, recommendedEmulators, featuredGames };
}
}); });
function ErrorComponent (data: ErrorComponentProps)
{
return <div className="flex items-center justify-center h-64">
<div role="alert" className="alert alert-error alert-soft max-w-sm">
<span>Failed to load store data.</span>
<p>{data.error.message}</p>
</div>
</div>;
}
// ── Loading skeleton ─────────────────────────────────────────────────────── function Main (data: { games?: FrontEndGameTypeDetailed[]; })
function LoadingSkeleton ()
{ {
return ( const [selectedGame, setSelectedGame] = useState(0);
<div className="flex flex-col gap-6 px-6 py-4 animate-pulse">
{/* Missing section */}
<div className="grid grid-cols-3 gap-3">
{[1, 2, 3].map((i) => <div key={i} className="skeleton h-40 rounded-2xl" />)}
</div>
{/* Emulators */}
<div className="grid grid-cols-6 gap-3">
{[1, 2, 3, 4, 5, 6].map((i) => <div key={i} className="skeleton h-36 rounded-2xl" />)}
</div>
{/* Games */}
<div className="grid grid-cols-4 gap-3">
{[1, 2, 3, 4].map((i) => <div key={i} className="skeleton h-44 rounded-2xl" />)}
</div>
</div>
);
}
function Main (data: { children?: any; games: FrontEndGameTypeDetailed[]; })
{
const [selectedGame, setSelectedGame] = useState(new Date().getSeconds() % data.games.length);
const [nextSwitch, setNextSwitch] = useState(new Date().getTime() + 10000); const [nextSwitch, setNextSwitch] = useState(new Date().getTime() + 10000);
const progressRef = useRef<HTMLProgressElement>(null); const progressRef = useRef<HTMLProgressElement>(null);
const { ref, focusKey } = useFocusable({ focusKey: 'main-featured-area' }); const { ref, focusKey } = useFocusable({ focusKey: 'main-featured-area' });
const game = data.games[selectedGame]; const game = data.games ? data.games[selectedGame] : undefined;
useInterval(() => useInterval(() =>
{ {
setSelectedGame(current => (current + 1) % data.games.length); if (!data.games) return;
setSelectedGame(current => (current + 1) % data.games!.length);
setNextSwitch(new Date().getTime() + 10000); setNextSwitch(new Date().getTime() + 10000);
}, 10000); }, 10000);
useEffect(() =>
{
if (!data.games) return;
setSelectedGame(new Date().getSeconds() % data.games.length);
}, [data.games]);
useInterval(() => useInterval(() =>
{ {
var time = (nextSwitch - new Date().getTime()) / 10000; var time = (nextSwitch - new Date().getTime()) / 10000;
@ -81,18 +49,18 @@ function Main (data: { children?: any; games: FrontEndGameTypeDetailed[]; })
}, 10); }, 10);
const storeContext = useContext(StoreContext); const storeContext = useContext(StoreContext);
const previewUrl = new URL(`${RPC_URL(__HOST__)}${data.games[selectedGame].path_cover}`); const previewUrl = data.games ? new URL(`${RPC_URL(__HOST__)}${data.games[selectedGame].path_cover}`) : undefined;
previewUrl.searchParams.set('blur', '16'); previewUrl?.searchParams.set('blur', '16');
return <div ref={ref} className='flex sm:flex-wrap md:flex-nowrap group-focusable p-4 mt-4 gap-4'> return <div ref={ref} className='flex sm:flex-wrap md:flex-nowrap group-focusable p-4 mt-4 gap-4'>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<div key={selectedGame} className="flex transition-all duration-500 flex-col sm:32 md:h-64 rounded-3xl overflow-hidden shadow-black/5 shadow-xl grow"> {game ? <div key={selectedGame} className="flex transition-all duration-500 flex-col rounded-3xl overflow-hidden shadow-black/5 shadow-xl w-full">
<div className='flex relative h-full overflow-hidden'> <div className='flex relative h-full overflow-hidden'>
<div className='absolute w-full h-full z-0 bg-base-200'> <div className='absolute w-full h-full z-0 bg-base-200'>
<img key={selectedGame} <img key={selectedGame}
className='w-full h-full object-cover transition-all duration-500 ease-out scale-110 opacity-0 z-0 mask-l-from-0' className='w-full h-full object-cover transition-all duration-500 ease-out scale-110 opacity-0 z-0 mask-l-from-0'
src={previewUrl.href} src={previewUrl?.href}
onLoad={(e) => onLoad={(e) =>
{ {
e.currentTarget.classList.toggle('opacity-0', false); e.currentTarget.classList.toggle('opacity-0', false);
@ -101,11 +69,11 @@ function Main (data: { children?: any; games: FrontEndGameTypeDetailed[]; })
/> />
</div> </div>
<div key={selectedGame} className='flex sm:flex-wrap md:flex-nowrap grow z-1 p-8 opacity-0 animate-fade-in h-full items-end gap-4 sm:justify-end md:justify-between'> <div key={selectedGame} className='flex sm:flex-wrap md:flex-nowrap grow z-1 p-8 opacity-0 animate-fade-in h-full items-end gap-4 sm:justify-end md:justify-between'>
<div className='flex gap-4 max-h-full z-1 grow'> <div className='flex gap-4 max-h-full z-1 grow md:h-full'>
<div className='flex sm:portrait:flex-wrap sm:portrait:grow gap-4 max-h-full justify-center'> <div className='flex sm:portrait:flex-wrap sm:portrait:grow gap-4 max-h-full justify-center'>
<div className='relative rounded-3xl max-w-xs overflow-hidden'> <div className='relative rounded-3xl max-w-xs h-48 overflow-hidden'>
<div className='flex absolute bottom-4 left-4 size-8 bg-base-content text-base-100 rounded-full items-center justify-center shadow-lg'><HardDrive /></div> <div className='flex absolute bottom-4 left-4 size-8 bg-base-content text-base-100 rounded-full items-center justify-center shadow-lg'><HardDrive /></div>
<img className='object-cover w-full h-full' src={`${RPC_URL(__HOST__)}${data.games[selectedGame].path_cover}`} /> {!!data.games && <img className='object-cover w-full h-full' src={`${RPC_URL(__HOST__)}${data.games[selectedGame].path_cover}`} />}
</div> </div>
<div className='flex flex-col gap-2 py-3 max-w-md'> <div className='flex flex-col gap-2 py-3 max-w-md'>
<h1 className='font-semibold text-3xl'>{game.name}</h1> <h1 className='font-semibold text-3xl'>{game.name}</h1>
@ -117,21 +85,19 @@ function Main (data: { children?: any; games: FrontEndGameTypeDetailed[]; })
<Button onAction={() => storeContext.showDetails('game', game.id.source, game.id.id, focusKey)} className='px-6 py-3 text-2xl! z-1 gap-2 focusable focusable-primary' id={'play-featured-btn'}> <Search /> Details</Button> <Button onAction={() => storeContext.showDetails('game', game.id.source, game.id.id, focusKey)} className='px-6 py-3 text-2xl! z-1 gap-2 focusable focusable-primary' id={'play-featured-btn'}> <Search /> Details</Button>
</div> </div>
</div> </div>
</div> : <div className='skeleton w-full rounded-3xl grow sm:h-64 z-15' />}
{data.children}
</div>
<div className='sm:flex sm:flex-wrap grow justify-stretch md:grid sm:landscape:grid-flow-col sm:auto-cols-[minmax(8rem,1fr)] md:grid-flow-row! auto-rows-fr landscape:min-w-xs gap-4'> <div className='sm:flex sm:flex-wrap grow justify-stretch md:grid sm:landscape:grid-flow-col sm:auto-cols-[minmax(8rem,1fr)] md:grid-flow-row! auto-rows-fr landscape:min-w-xs gap-4'>
{data.games.map((g, i) => {data.games?.map((g, i) =>
<div key={i} data-active={i === selectedGame} className='flex grow flex-col gap-1 transition-opacity duration-500 data-[active=true]:opacity-50 rounded-3xl bg-base-100 p-4 justify-center shadow-md'> <div key={i} data-active={i === selectedGame} className='flex grow flex-col gap-1 transition-opacity duration-500 data-[active=true]:opacity-50 rounded-3xl bg-base-100 p-4 justify-center shadow-md'>
<div className='flex gap-2'> <div className='flex gap-2'>
<img className='size-6' src={`${RPC_URL(__HOST__)}${game.path_platform_cover}`}></img> <img className='size-6' src={`${RPC_URL(__HOST__)}${g.path_platform_cover}`}></img>
<div className='flex gap-2 items-center grow'> <div className='flex gap-2 items-center grow'>
{g.name} {g.name}
</div> </div>
</div> </div>
{i === selectedGame && <progress ref={progressRef} className="progress progress-accent w-full" style={{ animationName: '' }} value={0} max="1"></progress>} {i === selectedGame && <progress ref={progressRef} className="progress progress-accent w-full" style={{ animationName: '' }} value={0} max="1"></progress>}
</div>)} </div>) ?? Array.from({ length: 3 }).map((_, i) => <div key={i} className="skeleton rounded-3xl"></div>)}
</div> </div>
</FocusContext> </FocusContext>
</div>; </div>;
@ -140,7 +106,9 @@ function Main (data: { children?: any; games: FrontEndGameTypeDetailed[]; })
export function RouteComponent () export function RouteComponent ()
{ {
const { focus } = useSearch({ from: '/store/tab' }); const { focus } = useSearch({ from: '/store/tab' });
const { crutialEmulators, recommendedEmulators, featuredGames } = Route.useLoaderData(); const { data: crucialEmulators, isSuccess } = useQuery({ ...queries.settings.autoEmulatorsQuery, select: (data) => data.filter(e => !e.exists && e.isCritical) });
const { data: featuredGames } = useQuery(queries.store.storeFeaturedGamesQuery);
const { data: recommendedEmulators } = useQuery(queries.store.storeEmulatorsRecommendedQuery);
const { focusKey, ref, focusSelf } = useFocusable({ focusKey: 'main-area', preferredChildFocusKey: focus ?? "recommended-emulators" }); const { focusKey, ref, focusSelf } = useFocusable({ focusKey: 'main-area', preferredChildFocusKey: focus ?? "recommended-emulators" });
const storeContext = useContext(StoreContext); const storeContext = useContext(StoreContext);
@ -152,15 +120,15 @@ export function RouteComponent ()
focusSelf({ instant: true }); focusSelf({ instant: true });
} }
}, [focus]); }, [focus, isSuccess]);
return ( return (
<div className='animate-slide-up' ref={ref}> <div className='animate-slide-up' ref={ref}>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
{!!featuredGames && <Main games={featuredGames} />} {<Main games={featuredGames} />}
{crutialEmulators.length > 0 && <MissingEmulatorsSection {!!crucialEmulators && crucialEmulators?.length > 0 && <MissingEmulatorsSection
onSelect={(id, focus) => storeContext.showDetails('emulator', 'store', id, focus)} onSelect={(id, focus) => storeContext.showDetails('emulator', 'store', id, focus)}
emulators={crutialEmulators} />} emulators={crucialEmulators} />}
<div className='pt-4'> <div className='pt-4'>
<EmulatorsSection <EmulatorsSection
id="recommended-emulators" id="recommended-emulators"
@ -177,7 +145,7 @@ export function RouteComponent ()
<StatsSection <StatsSection
romCount={1240} romCount={1240}
missingCount={crutialEmulators.length} missingCount={crucialEmulators?.length ?? 0}
/> />
</FocusContext> </FocusContext>
</div> </div>

View file

@ -6,9 +6,18 @@ import { mobileCheck } from "./utils";
let loopStarted = false; let loopStarted = false;
let isTouching = false; let isTouching = false;
type ActiveControlType = 'keyboard' | 'gamepad' | 'mouse' | 'touch' | undefined; type ActiveControlType = 'keyboard' | 'gamepad' | 'mouse' | 'touch' | undefined;
let activeControls: ActiveControlType = mobileCheck() ? 'touch' : 'mouse'; let activeControls: ActiveControlType = sessionStorage.getItem('active-controls') as any;
if (!activeControls)
{
if (mobileCheck())
{
activeControls = 'touch';
} else
{
activeControls = 'mouse';
}
}
let mouseUpdateTimeout: any | undefined = undefined; let mouseUpdateTimeout: any | undefined = undefined;
let touchStopTimeout: any | undefined = undefined;
const handleLoop = () => const handleLoop = () =>
{ {
@ -109,6 +118,13 @@ function focusControl (control: typeof activeControls)
if (activeControls != control) if (activeControls != control)
{ {
activeControls = control; activeControls = control;
if (control)
{
sessionStorage.setItem('active-controls', control);
} else
{
sessionStorage.removeItem('active-controls');
}
window.dispatchEvent(new CustomEvent('activecontrolschange', { detail: control })); window.dispatchEvent(new CustomEvent('activecontrolschange', { detail: control }));
if (control !== 'mouse') if (control !== 'mouse')
{ {

View file

@ -1,108 +1,11 @@
import { keepPreviousData, mutationOptions, queryOptions } from "@tanstack/react-query"; import system from "./queries/system";
import { rommApi, settingsApi, storeApi, systemApi } from "./clientApi"; import settings from "./queries/settings";
import toast from "react-hot-toast"; import romm from "./queries/romm";
import { getErrorMessage } from "react-error-boundary"; import store from "./queries/store";
export const drivesQuery = queryOptions({ export default {
queryKey: ['drives'], system,
queryFn: async () => settings,
{ romm,
const { data, error } = await systemApi.api.system.drives.get(); store
if (error) throw error; };
return data;
}
});
export const downloadDrivesQuery = queryOptions({
queryKey: ['drives', 'download'],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.drives.download.get();
if (error) throw error;
return data;
}
});
export const filesQuery = (currentPath: string | undefined, id: string) => queryOptions({
queryKey: ['files', currentPath ?? '', id],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.dirs.get({ query: { path: currentPath } });
if (error) throw error;
return data;
},
placeholderData: keepPreviousData
});
export const changeDownloadsMutation = mutationOptions({
mutationKey: ["setting", "downloads"],
mutationFn: async (value: any) =>
{
const response = await toast.promise(settingsApi.api.settings.path.download.put({ manualPath: value }).then(d =>
{
if (d.error) throw d.error;
return d.data;
}), {
success: e => `Download Moved to ${e}`,
loading: "Moving Download",
error: e => getErrorMessage(e) ?? "Error Moving Download"
});
return response;
}
});
export const gameQuery = (source: string, id: string) => queryOptions({
queryKey: ['game', source, id],
queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.game({ source })({ id }).get();
if (error) throw error;
return data;
},
});
export const autoEmulatorsQuery = queryOptions({
queryKey: ['auto-emulators'], queryFn: async () =>
{
const { data, error } = await settingsApi.api.settings.emulators.automatic.get();
if (error) throw error;
return data;
}
});
export const storeEmulatorsQuery = queryOptions({
queryKey: ['store-emulators'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.emulators.get();
if (error) throw error;
return data;
}
});
export const storeFeaturedGamesQuery = queryOptions({
queryKey: ['store-emulators', 'recommended'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.games.featured.get();
if (error) throw error;
return data;
}
});
export const storeEmulatorsRecommendedQuery = queryOptions({
queryKey: ['store-emulators', 'recommended'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.emulators.get({ query: { limit: 6, missing: true, orderBy: 'importance' } });
if (error) throw error;
return data;
}
});
export const storeEmulatorDetailsQuery = (id: string) => queryOptions({
queryKey: ['store-emulator', id], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.details.emulator({ id }).get();
if (error) throw error;
return data;
}
});

View file

@ -0,0 +1,79 @@
import { DefaultRommStaleTime, FrontEndId, GameListFilterType, RommLoginDataSchema, RPC_URL } from "@/shared/constants";
import { rommApi, settingsApi } from "../clientApi";
import { mutationOptions, queryOptions } from "@tanstack/react-query";
import z from "zod";
import { getCollectionApiCollectionsIdGetOptions, getCollectionsApiCollectionsGetOptions, getCurrentUserApiUsersMeGetOptions, statsApiStatsGetOptions } from "@/clients/romm/@tanstack/react-query.gen";
export default {
allGamesQuery: (filter?: GameListFilterType) => queryOptions({
queryKey: ['games', filter ?? 'all'],
queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.games.get({ query: filter });
if (error) throw error;
return data;
}
}),
gameQuery: (source: string, id: string) => queryOptions({
queryKey: ['game', source, id],
queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.game({ source })({ id }).get();
if (error) throw error;
return data;
},
}),
rommLogoutMutation: mutationOptions({ mutationKey: ["romm", "auth", "logout"], mutationFn: () => rommApi.api.romm.logout.post() }),
rommQrLoginMutation: mutationOptions({
mutationKey: ['login', 'qr', 'cancel'],
mutationFn: () => rommApi.api.romm.login.romm.post()
}),
rommLoginMutation: mutationOptions({
mutationKey: ["romm", "login"],
mutationFn: async (data: z.infer<typeof RommLoginDataSchema>) =>
{
const { error } = await rommApi.api.romm.login.post({ username: data.username, password: data.password, host: data.hostname });
if (error) throw error;
},
onSuccess: (d, v, r, c) =>
{
c.client.invalidateQueries({ queryKey: ['romm', 'auth'] });
},
onError: (e) =>
{
console.error(e);
},
}),
rommUserQuery: () => queryOptions({
...getCurrentUserApiUsersMeGetOptions(),
queryKey: ['romm', 'auth', "login"],
refetchOnWindowFocus: false,
retry: 0
}),
rommGetOptionsQuery: () => queryOptions({
...statsApiStatsGetOptions(),
refetchInterval: 30000,
retry: false,
}),
rommHasPasswordQuery: queryOptions({ queryKey: ['romm', 'auth', 'passLength'], queryFn: () => rommApi.api.romm.login.get().then(d => d.data?.hasPassword as boolean) }),
rommHostnameQuery: queryOptions({ queryKey: ['romm', 'auth', 'hostname'], queryFn: () => settingsApi.api.settings({ id: 'rommAddress' }).get().then(d => d.data?.value as string) }),
rommUsernameQuery: queryOptions({ queryKey: ['romm', 'auth', 'username'], queryFn: () => settingsApi.api.settings({ id: 'rommUser' }).get().then(d => d.data?.value as string) }),
deleteGameMutation: (id: FrontEndId) => mutationOptions({
mutationKey: ['delete', id],
mutationFn: () => rommApi.api.romm.game({ source: id.source })({ id: id.id }).delete()
}),
getCollectionsQuery: () => queryOptions({
...getCollectionsApiCollectionsGetOptions(),
refetchOnWindowFocus: false,
staleTime: DefaultRommStaleTime
}),
getCollectionQuery: (id: number) => queryOptions({ ...getCollectionApiCollectionsIdGetOptions({ path: { id } }) }),
platformQuery: (source: string, id: string) => queryOptions({
queryKey: ['platform', source, id], queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.platforms({ source })({ id }).get();
if (error) throw error;
return data;
}, staleTime: DefaultRommStaleTime
})
};

View file

@ -0,0 +1,134 @@
import { mutationOptions, queryOptions } from "@tanstack/react-query";
import { getErrorMessage } from "react-error-boundary";
import toast from "react-hot-toast";
import { rommApi, settingsApi } from "../clientApi";
export default {
changeDownloadsMutation: mutationOptions({
mutationKey: ["setting", "downloads"],
mutationFn: async (value: any) =>
{
const response = await toast.promise(settingsApi.api.settings.path.download.put({ manualPath: value }).then(d =>
{
if (d.error) throw d.error;
return d.data;
}), {
success: e => `Download Moved to ${e}`,
loading: "Moving Download",
error: e => getErrorMessage(e) ?? "Error Moving Download"
});
return response;
}
}),
autoEmulatorsQuery: queryOptions({
queryKey: ['auto-emulators'], queryFn: async () =>
{
const { data, error } = await settingsApi.api.settings.emulators.automatic.get();
if (error) throw error;
return data;
}
}),
twitchLogoutMutation: mutationOptions({
mutationKey: ['twitch', 'logout'],
mutationFn: () =>
{
return rommApi.api.romm.logout.twitch.post();
}
}),
twitchLoginMutation: mutationOptions({
mutationKey: ['twitch', 'login'],
mutationFn: (openInBrowser: boolean) =>
{
return rommApi.api.romm.login.twitch.post({ openInBrowser });
}
}),
twitchLoginVerificationQuery: queryOptions({
queryKey: ['twitch', 'login', 'status'],
retry (failureCount, error)
{
if ((error as any).status === 404)
{
return false;
}
return failureCount < 3;
},
queryFn: async () =>
{
const { data, error, status } = await rommApi.api.romm.login.twitch.get();
if (error) throw { ...error, status };
return data;
}
}),
customEmulatorsQuery: queryOptions({
queryKey: ['custom-emulators'], queryFn: async () =>
{
const { data, error } = await settingsApi.api.settings.emulators.custom.get();
if (error) throw error;
return data;
}
}),
customEmulatorAddMutation: mutationOptions({
mutationKey: ['emulator', 'custom', 'add'],
mutationFn: async (id: string) =>
{
const { data, error } = await settingsApi.api.settings.emulators.custom({ id }).put({ value: '' });
if (error) throw error;
return data;
},
onSuccess: (d, v, r, ctx) => ctx.client.invalidateQueries({ queryKey: ['custom-emulators'] })
}),
customEmulatorDeleteMutation: (id: string) => mutationOptions({
mutationKey: ["emulator", id, 'delete'],
mutationFn: async () =>
{
const { error } = await settingsApi.api.settings.emulators.custom({ id: id }).delete();
if (error) throw error;
},
onSuccess: (d, v, r, ctx) =>
{
ctx.client.invalidateQueries({ queryKey: ['custom-emulators'] });
ctx.client.invalidateQueries({ queryKey: ["auto-emulators"] });
}
}),
setCustomEmulatorMutation: (id: string, onSuccess?: (value: string) => void) => mutationOptions({
mutationKey: ["emulator", id, 'set'],
mutationFn: async (value: string) => settingsApi.api.settings.emulators.custom({ id: id }).put({ value }),
onSuccess: (d, v, r, ctx) =>
{
ctx.client.invalidateQueries({ queryKey: ["emulator", id] });
ctx.client.invalidateQueries({ queryKey: ["auto-emulators"] });
onSuccess?.(v);
}
}),
customEmulatorRemoveValueQuery: (id?: string) => queryOptions({
enabled: !!id,
queryKey: ["emulator", id],
queryFn: async () =>
{
const { data: value, error } = await settingsApi.api.settings.emulators.custom({ id: id! }).get();
if (error) throw error;
return value;
},
}),
setSettingMutation: (id?: string) => mutationOptions({
mutationKey: ["setting", id],
mutationFn: async (value: any) =>
{
const response = await settingsApi.api.settings({ id: id! }).post({ value });
if (response.error) throw response.error;
return response.data;
}
}),
getSettingQuery: (id: string | undefined) => queryOptions({
enabled: !!id,
queryKey: ["setting", id],
queryFn: async () =>
{
const { data: value, error } = await settingsApi.api.settings({ id: id! }).get();
if (error) throw error;
return value.value;
},
})
};

View file

@ -0,0 +1,58 @@
import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
import { rommApi, storeApi } from "../clientApi";
import { FrontEndGameType } from "@/shared/constants";
export default {
storeEmulatorsQuery: queryOptions({
queryKey: ['store-emulators'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.emulators.get();
if (error) throw error;
return data;
}
}),
storeFeaturedGamesQuery: queryOptions({
queryKey: ['store-emulators', 'featured'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.games.featured.get();
if (error) throw error;
return data;
}
}),
storeEmulatorsRecommendedQuery: queryOptions({
queryKey: ['store-emulators', 'recommended'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.emulators.get({ query: { limit: 6, missing: true, orderBy: 'importance' } });
if (error) throw error;
return data;
}
}),
storeEmulatorDetailsQuery: (id: string) => queryOptions({
queryKey: ['store-emulator', id], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.details.emulator({ id }).get();
if (error) throw error;
return data;
}
}),
storeGamesInfiniteQuery: infiniteQueryOptions<{ data: FrontEndGameType[], nextPage: number; }>({
initialPageParam: 0,
queryKey: ['store-games'],
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
queryFn: async (data) =>
{
const pageParam = data.pageParam as number;
const { data: games, error } = await rommApi.api.romm.games.get({ query: { source: 'store', offset: pageParam * 10, limit: 10 } });
if (error) throw error;
return { data: games.games, nextPage: pageParam + 1 };
}
}),
storeGetStatsQuery: queryOptions({
queryKey: ['store', 'stats'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.stats.get();
if (error) throw error;
return data;
}
})
};

View file

@ -0,0 +1,51 @@
import { keepPreviousData, mutationOptions, queryOptions } from "@tanstack/react-query";
import { systemApi } from "../clientApi";
export default {
drivesQuery: queryOptions({
queryKey: ['drives'],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.drives.get();
if (error) throw error;
return data;
}
}),
downloadDrivesQuery: queryOptions({
queryKey: ['drives', 'download'],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.drives.download.get();
if (error) throw error;
return data;
}
}),
filesQuery: (currentPath: string | undefined, id: string) => queryOptions({
queryKey: ['files', currentPath ?? '', id],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.dirs.get({ query: { path: currentPath } });
if (error) throw error;
return data;
},
placeholderData: keepPreviousData
}),
systemInfoQuery: queryOptions({ queryKey: ['system-info'], queryFn: () => systemApi.api.system.info.get() }),
createFolderMutation: (id: string) => mutationOptions({
mutationKey: ['create', 'folder', id],
mutationFn: async ({ name, dirname }: { name: string | undefined, dirname: string; }) =>
{
if (!name) return;
const { error } = await systemApi.api.system.dirs.put({ name, dirname: dirname });
if (error) throw error.value;
},
}),
closeMutation: mutationOptions({
mutationKey: ['close'], mutationFn: async () =>
{
const { error } = await systemApi.api.system.exit.post();
if (error) throw error;
}
})
};

View file

@ -0,0 +1,60 @@
/// <reference lib="webworker" />
declare const self: ServiceWorkerGlobalScope;
const SHELL = 'shell-v1';
async function cacheWithoutVary (cache: Cache, url: string)
{
const response = await fetch(url);
const cleaned = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: (() =>
{
const h = new Headers(response.headers);
h.delete('Vary');
return h;
})()
});
await cache.put(url, cleaned);
}
self.addEventListener('install', (event: ExtendableEvent) =>
{
event.waitUntil(
caches.open(SHELL).then(cache => cacheWithoutVary(cache, '/'))
);
self.skipWaiting();
});
self.addEventListener('activate', (event: ExtendableEvent) =>
{
// Clean up old caches when you bump SHELL version
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== SHELL).map(k => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event: FetchEvent) =>
{
if (event.request.mode !== 'navigate') return;
event.respondWith(
fetch(event.request)
.then(response =>
{
const vary = response.headers.get('Vary');
if (!vary?.includes('*'))
{
caches.open(SHELL).then(cache => cache.put(event.request, response.clone()));
}
return response;
})
.catch(() =>
caches.match('/').then(cached => cached ?? Response.error())
)
);
});

View file

@ -3,7 +3,7 @@ import { GamepadButtonEvent } from "./gamepads";
import { dispatchFocusedEvent, GetFocusedTree } from "./spatialNavigation"; import { dispatchFocusedEvent, GetFocusedTree } from "./spatialNavigation";
import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation"; import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
const shortcutMap = new Map<string, Shortcut[]>(); const shortcutMap = new Map<string, (() => Shortcut[])[]>();
const conflictSet = new Set<number>(); const conflictSet = new Set<number>();
let hadEnterDown = false; let hadEnterDown = false;
@ -66,7 +66,8 @@ export function useShortcutContext ()
const focusKey = getCurrentFocusKey(); const focusKey = getCurrentFocusKey();
const newArray = GetFocusedTree(focusKey) const newArray = GetFocusedTree(focusKey)
.filter(f => shortcutMap.has(f)) .filter(f => shortcutMap.has(f))
.flatMap(f => shortcutMap.get(f)!.map(s => ({ key: f, ...s }))) .flatMap(f => shortcutMap.get(f)!.map(s => ({ key: f, handler: s })))
.flatMap(kvp => kvp.handler().map(s => ({ key: kvp.key, ...s })))
.filter(s => .filter(s =>
{ {
const empty = !conflictSet.has(s.button); const empty = !conflictSet.has(s.button);
@ -193,12 +194,20 @@ export function useShortcuts (focusKey: string, build: () => Shortcut[], ...deps
{ {
useEffect(() => useEffect(() =>
{ {
shortcutMap.set(focusKey, build()); const array = shortcutMap.get(focusKey) ?? [];
array.push(build);
shortcutMap.set(focusKey, array);
markDirtyThrottled(); markDirtyThrottled();
return () => return () =>
{ {
shortcutMap.delete(focusKey); const array = shortcutMap.get(focusKey);
if (array)
{
const index = array.indexOf(build);
array?.splice(index, 1);
}
markDirtyThrottled(); markDirtyThrottled();
}; };
}, [...deps, focusKey]); }, [...deps, focusKey]);

View file

@ -1,11 +1,8 @@
import { LocalSettingsSchema, LocalSettingsType } from "@/shared/constants"; import { LocalSettingsSchema, LocalSettingsType } from "@/shared/constants";
import { doesFocusableExist, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation"; import { doesFocusableExist, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { Ref, RefObject, useEffect, useRef, useState } from "react"; import { RefObject, useEffect, useRef, useState } from "react";
import { useLocalStorage } from "usehooks-ts"; import { useLocalStorage } from "usehooks-ts";
import { jobsApi } from "./clientApi"; import { jobsApi } from "./clientApi";
import { EdenWS } from "@elysiajs/eden/treaty";
import { InputSchema } from "elysia/types";
import { Treaty } from "@elysiajs/eden";
import { JobsAPIType } from "@/bun/api/rpc"; import { JobsAPIType } from "@/bun/api/rpc";
export function selfFocusSmart (shouldFocus: boolean, focusSelf: () => void) export function selfFocusSmart (shouldFocus: boolean, focusSelf: () => void)
@ -67,7 +64,7 @@ export function useScrollSave (data: ScrollSaveParams)
export function mobileCheck () export function mobileCheck ()
{ {
let check = false; let check = false;
(function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera); (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || (window as any).opera);
return check; return check;
}; };

View file

@ -49,6 +49,8 @@ export const GameListFilterSchema = z.object({
source: z.string().optional(), source: z.string().optional(),
}); });
export const RommLoginDataSchema = z.object({ hostname: z.url(), username: z.string(), password: z.string() });
export type GameListFilterType = z.infer<typeof GameListFilterSchema>; export type GameListFilterType = z.infer<typeof GameListFilterSchema>;
export const DirSchema = z.object({ name: z.string(), parentPath: z.string(), isDirectory: z.boolean() }); export const DirSchema = z.object({ name: z.string(), parentPath: z.string(), isDirectory: z.boolean() });

View file

@ -1,4 +1,4 @@
import { expect, test, mock } from 'bun:test'; import { expect, test } from 'bun:test';
test("uses custom emulator", async () => test("uses custom emulator", async () =>
{ {

View file

@ -17,7 +17,6 @@
"jsx": "react-jsx", "jsx": "react-jsx",
"strict": true, "strict": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"paths": { "paths": {
"@/*": [ "@/*": [

View file

@ -1,4 +1,4 @@
import { defineConfig, Plugin } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import tailwindcss from '@tailwindcss/vite'; import tailwindcss from '@tailwindcss/vite';
import { tanstackRouter } from '@tanstack/router-plugin/vite'; import { tanstackRouter } from '@tanstack/router-plugin/vite';
@ -8,6 +8,7 @@ import staticAssetsPlugin from 'vite-static-assets-plugin';
import os from 'node:os'; import os from 'node:os';
import tsconfigPaths from 'vite-tsconfig-paths'; import tsconfigPaths from 'vite-tsconfig-paths';
import { host } from "./src/bun/utils/host"; import { host } from "./src/bun/utils/host";
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig(({ command }) => export default defineConfig(({ command }) =>
{ {
@ -59,21 +60,22 @@ export default defineConfig(({ command }) =>
manualChunks: (id manualChunks: (id
) => ) =>
{ {
if (id.includes('@emulatorjs'))
{
return 'emulatorjs';
}
if (id
.includes
('node_modules'))
{
return 'vendor';
}
if (id.includes('@emulatorjs'))
return 'emulatorjs';
if (id.includes('clients/romm'))
return 'clients';
if (id.includes('node_modules/lucide-react'))
return 'lucide';
if (id.includes('node_modules/zod'))
return 'zod';
if (id.includes('node_modules/@tanstack'))
return 'tanstack';
console.log(id);
if (id.includes('node_modules'))
return 'vendor';
if (id.endsWith('SvgIcon.tsx')) if (id.endsWith('SvgIcon.tsx'))
{
return 'icons'; return 'icons';
}
return null; return null;
}, },