feat: Implemented emulator installation

feat: Updated romm API version
feat: Updated es-de rules
feat: Added tabs to game details
refactor: returned to global query definitions to help with typescript performance
This commit is contained in:
Simeon Radivoev 2026-03-22 01:11:21 +02:00
parent cf6fff6fac
commit 3750e9ed8f
Signed by: simeonradivoev
GPG key ID: 7611A451D2A5D37A
103 changed files with 4888 additions and 1632 deletions

View file

@ -33,6 +33,7 @@ export interface GameCardParams
onFocus?: GameCardFocusHandler;
onBlur?: (id: string) => void;
clickFocuses?: boolean;
previewClassName?: string;
}
export default function CardElement (data: GameCardParams & InteractParams)
@ -53,7 +54,7 @@ export default function CardElement (data: GameCardParams & InteractParams)
role="button"
ref={ref}
style={{
scrollSnapAlign: "center"
scrollSnapAlign: isPointer ? "center" : "none"
}}
onFocus={focusSelf}
onDoubleClick={e => data.onAction?.(e.nativeEvent)}
@ -74,7 +75,7 @@ export default function CardElement (data: GameCardParams & InteractParams)
classNames({ "h-full": typeof data.preview === "string" })
)}>
{typeof data.preview === "string" ? (
<img draggable={false} className={classNames("object-cover w-full h-full", { "animate-rotate-small": focused && !isPointer })} src={data.preview} ></img>
<img draggable={false} className={classNames("object-cover w-full h-full", data.previewClassName, { "animate-rotate-small": focused && !isPointer })} src={data.preview} ></img>
) : (
typeof data.preview === 'function' ? data.preview({ focused }) : data.preview
)}

View file

@ -2,10 +2,8 @@ import { RPC_URL } from "@/shared/constants";
import { useSuspenseQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { CardList, GameMetaExtra } from "./CardList";
import { SaveSource } from "../scripts/spatialNavigation";
import { GameCardFocusHandler } from "./CardElement";
import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import queries from "../scripts/queries";
import { getCollectionsQuery } from "@queries/romm";
export default function CollectionList (data: {
id: string,
@ -17,12 +15,11 @@ export default function CollectionList (data: {
})
{
const navigate = useNavigate();
const { data: collections } = useSuspenseQuery(queries.romm.getCollectionsQuery());
const { data: collections } = useSuspenseQuery(getCollectionsQuery());
const handleDefaultSelect = (id: string) =>
{
SaveSource('game-list', { search: { focus: getCurrentFocusKey() } });
navigate({ to: `/collection/${id}`, viewTransition: { types: ['zoom-in'] } });
navigate({ to: `/collection/${id}` });
};
return (
@ -36,7 +33,7 @@ export default function CollectionList (data: {
id: String(g.id),
title: g.name,
focusKey: `collection-${g.id}`,
subtitle: g.user__username,
subtitle: g.owner_username,
previewUrl: `${RPC_URL(__HOST__)}/api/romm/${g.path_covers_large[0]}`,
badges: [
<span className="text-lg font-bold badge bg-base-100 shadow-md shadow-base-300 h-8 rounded-full mr-2">

View file

@ -10,6 +10,8 @@ import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/
import { PopNavigateSource } from '../scripts/spatialNavigation';
import { GameListFilterType } from '@/shared/constants';
import { GameCardFocusHandler } from './CardElement';
import { Router } from '..';
import { HandleGoBack } from '../scripts/utils';
export interface CollectionsDetailParams
{
@ -30,7 +32,7 @@ export function CollectionsDetail (data: CollectionsDetailParams)
preferredChildFocusKey: `${focusKey}-list`,
});
useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: () => PopNavigateSource('game-list', '/') }]);
useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: HandleGoBack }]);
const { shortcuts } = useShortcutContext();
const handleScroll: GameCardFocusHandler = (id, node, details) =>

View file

@ -1,6 +1,6 @@
import { FocusContext, FocusDetails, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { FocusContext, FocusDetails, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames";
import { JSX, useContext, useEffect } from "react";
import { JSX, useContext, useEffect, useState } from "react";
import { twMerge } from "tailwind-merge";
import { X } from "lucide-react";
import { GamePadButtonCode, Shortcut, useShortcuts } from "../scripts/shortcuts";
@ -67,21 +67,61 @@ export interface DialogEntry
shortcuts?: Shortcut[];
}
export function useContextDialog (id: string, data: { content?: JSX.Element; className?: string; preferredChildFocusKey?: string; onClose?: () => void; })
{
const [open, setOpen] = useState(false);
const [sourceFocusKey, setSourceFocusKey] = useState<string | undefined>(undefined);
const dialog = <ContextDialog id={id} open={open} close={() =>
{
setOpen(false);
data.onClose?.();
}} className={data.className} sourceFocusKey={sourceFocusKey} preferredChildFocusKey={data.preferredChildFocusKey}>
{data.content}
</ContextDialog>;
return {
dialog,
open,
setOpen: (value: boolean, sourceFocusKey?: string) =>
{
if (value === open) return;
if (value)
{
setOpen(true);
setSourceFocusKey(sourceFocusKey);
} else
{
setOpen(false);
if (sourceFocusKey)
{
setFocus(sourceFocusKey);
}
}
}
};
}
export function ContextDialog (data: {
id: string,
children: any | any[],
open: boolean,
close: () => void;
close: (open: boolean) => void;
className?: string;
preferredChildFocusKey?: string;
sourceFocusKey?: string;
})
{
const { ref, focusKey, focusSelf } = useFocusable({
focusable: data.open,
focusKey: `${data.id}-context-dialog`,
isFocusBoundary: true,
saveLastFocusedChild: !data.preferredChildFocusKey,
preferredChildFocusKey: data.preferredChildFocusKey
});
const handleClose = () =>
{
data.close(false);
};
useEffect(() =>
{
if (data.open)
@ -93,22 +133,16 @@ export function ContextDialog (data: {
useShortcuts(focusKey, () => data.open ? [{
label: "Close",
button: GamePadButtonCode.B,
action: () =>
{
data.close();
}
action: handleClose
}] : [], [data.open]);
return <dialog ref={ref} open={data.open} closedby="any" className={
twMerge("fixed modal cursor-pointer bg-base-300/80 backdrop-brightness-50 duration-300 ease-in-out transition-all text-base-content",
classNames({ "opacity-0": !data.open }))
}
onClick={() =>
{
if (data.open) data.close();
}}>
onClick={handleClose}>
<FocusContext value={focusKey}>
<ContextDialogContext value={{ id: data.id, close: data.close }} >
<ContextDialogContext value={{ id: data.id, close: handleClose }} >
<div
className={twMerge(
"bg-base-100/80 delay-200 rounded-4xl sm:p-4 md:p-6 sm:min-w-[80vw] md:min-w-[20vw] cursor-auto",

View file

@ -12,9 +12,9 @@ import { GamePadButtonCode, Shortcut, useShortcuts } from "../scripts/shortcuts"
import SvgIcon from "./SvgIcon";
import { Button } from "./options/Button";
import toast from "react-hot-toast";
import queries from "../scripts/queries";
import { FilePickerContext } from "../scripts/contexts";
import useActiveControl from "../scripts/gamepads";
import { createFolderMutation, drivesQuery, filesQuery } from "@queries/system";
function List (data: {
id: string,
@ -113,7 +113,7 @@ function NewFolderOption (data: { id: string, dirname: string; })
const { refetchFiles } = useContext(FilePickerContext);
const [name, setName] = useState<string | undefined>();
const createMutation = useMutation({
...queries.system.createFolderMutation(data.id),
...createFolderMutation(data.id),
onError: (e) => toast.error(e.message ?? 'Error Creating New Folder'),
onSuccess: (d, v, r, cx) =>
{
@ -228,8 +228,8 @@ export default function FilePicker (data: {
{
const [currentPath, setCurrentPath] = useState<string | undefined>(data.startingPath);
const { data: files, refetch: refetchFiles, isLoading: filesLoading } = useQuery(queries.system.filesQuery(currentPath, data.id));
const { data: drives, isLoading: drivesLoading } = useQuery(queries.system.drivesQuery);
const { data: files, refetch: refetchFiles, isLoading: filesLoading } = useQuery(filesQuery(currentPath, data.id));
const { data: drives, isLoading: drivesLoading } = useQuery(drivesQuery);
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];

View file

@ -1,17 +1,19 @@
import
{
FocusContext,
setFocus,
useFocusable,
} from "@noriginmedia/norigin-spatial-navigation";
import SvgIcon from "./SvgIcon";
import { twMerge } from "tailwind-merge";
import { useEffect } from "react";
import { GamePadButtonCode, useShortcuts } from "../scripts/shortcuts";
function FilterCat (
data: {
id: string;
children?: any;
active: boolean;
hasFocusedPeer: boolean;
} & FilterOption & FocusParams,
)
{
@ -26,9 +28,10 @@ function FilterCat (
aria-selected={data.active}
ref={ref}
onClick={focusSelf}
className={"sm:text-sm sm:px-2 flex md:px-4 items-center justify-center rounded-full transition-all md:text-lg focusable focusable-primary hover:not-focused:not-aria-selected:bg-base-content/40 not-focused:cursor-pointer aria-selected:bg-base-content aria-selected:text-base-300 aria-selected:drop-shadow aria-selected:cursor-default active:bg-accent! active:text-accent-content! active:ring-offset-7 active:ring-offset-base-content select-none"}
className={"sm:text-sm sm:px-2 flex md:px-4 items-center justify-center rounded-full transition-all md:text-lg focusable focusable-primary hover:not-focused:not-aria-selected:bg-base-content/40 not-focused:cursor-pointer aria-selected:bg-base-content aria-selected:text-base-300 aria-selected:drop-shadow aria-selected:cursor-default active:bg-accent! active:text-accent-content! active:ring-offset-7 active:ring-offset-base-content select-none gap-1"}
>
{data.children ?? data.label}
{data.icon ? <><div className="sm:portrait:px-2">{data.icon}</div><div className="sm:portrait:hidden md:inline">{data.children ?? data.label}</div></> : <div>{data.children ?? data.label}</div>}
</li>
);
}
@ -39,6 +42,8 @@ export function FilterUI (data: {
setSelected: (id: string) => void;
containerClassName?: string;
className?: string;
rootFocusKey?: string;
showShortcuts?: boolean;
})
{
const defaultFocus = Object.entries(data.options).filter(o => o[1].selected)[0]?.[0];
@ -50,29 +55,72 @@ export function FilterUI (data: {
trackChildren: true
});
if (data.rootFocusKey)
{
useShortcuts(data.rootFocusKey, () => [
{
action: (e) =>
{
const filterKeys = Object.keys(data.options);
const filterIndex = Math.max(0, filterKeys.findIndex(f => data.options[f].selected));
const selectedFilterIndex = Math.min(filterIndex + 1, filterKeys.length - 1);
const newFilter = filterKeys[selectedFilterIndex];
if (!data.options[newFilter].selected)
{
data.setSelected(newFilter);
}
},
button: GamePadButtonCode.R1
},
{
action: (e) =>
{
const filterKeys = Object.keys(data.options);
const filterIndex = Math.max(0, filterKeys.findIndex(f => data.options[f as any].selected));
const selectedFilterIndex = Math.max(0, filterIndex - 1,);
const newFilter = filterKeys[selectedFilterIndex];
if (!data.options[newFilter].selected)
data.setSelected(newFilter);
},
button: GamePadButtonCode.L1
}], [data.options]);
}
useEffect(() =>
{
if (hasFocusedChild)
{
setFocus(`${data.id}-${defaultFocus}`);
}
}, [hasFocusedChild, defaultFocus, data.id]);
return (
<div
ref={ref}
className={data.containerClassName}
style={{ viewTransitionName: `filter-${data.id}` }}
>
<FocusContext.Provider value={focusKey}>
<ul className={twMerge("flex flex-row bg-base-100 rounded-full p-1 drop-shadow-sm sm:portrait:h-12 sm:landscape:h-9 md:h-14!", data.className)}>
<li className=" flex px-4 items-center justify-center rounded-full">
{!!data.rootFocusKey && (data.showShortcuts ?? true) && <li className=" flex px-4 items-center justify-center rounded-full">
<SvgIcon className="sm:size-5 md:size-8" icon="steamdeck_button_l1_outline" />
</li>
</li>}
{Object.entries(data.options)?.map(([id, option]) => (
<FilterCat
hasFocusedPeer={hasFocusedChild}
id={`${data.id}-${id}`}
key={id}
onFocus={() => data.setSelected(id)}
onFocus={() =>
{
if (!option.selected)
data.setSelected(id);
}}
active={option.selected}
{...option}
/>
))}
<li className="flex px-4 items-center justify-center rounded-full">
{!!data.rootFocusKey && (data.showShortcuts ?? true) && <li className="flex px-4 items-center justify-center rounded-full">
<SvgIcon className="sm:size-5 md:size-8" icon="steamdeck_button_r1_outline" />
</li>
</li>}
</ul>
</FocusContext.Provider>
</div>

View file

@ -42,7 +42,6 @@ export default function FocusDots (data: {
scrollElement?: RefObject<HTMLElement | null>;
})
{
const focusedKey = useGlobalFocus();
let elements = useMemo(() =>
{
@ -62,7 +61,7 @@ export default function FocusDots (data: {
return childrenArray.map((c, i) =>
{
return <ScrollDot parent={data.scrollElement!} index={i} peers={childrenArray as HTMLElement[]} />;
return <ScrollDot key={i} parent={data.scrollElement!} index={i} peers={childrenArray as HTMLElement[]} />;
});
} else
{

View file

@ -1,18 +1,15 @@
import { FrontEndGameType, FrontEndId, RPC_URL } from "@/shared/constants";
import CardElement from "./CardElement";
import { SaveSource } from "../scripts/spatialNavigation";
import { Router } from "..";
import { HardDrive } from "lucide-react";
import { FileQuestion, HardDrive, Store } from "lucide-react";
import { JSX } from "react";
import { FOCUS_KEYS } from "../scripts/types";
export default function FrontEndGameCard (data: { index: number, game: FrontEndGameType; } & FocusParams & InteractParams)
export default function FrontEndGameCard (data: { index: number, game: FrontEndGameType; showSource?: boolean; } & FocusParams & InteractParams)
{
function handleDefaultSelect (id: FrontEndId, source: string | null, sourceId: string | null)
{
SaveSource('details', { search: { focus: FOCUS_KEYS.GAME_CARD(data.game.id.id) } });
console.log({ id: String(sourceId ?? id.id), source: source ?? id.source });
Router.navigate({ to: '/game/$source/$id', params: { id: String(sourceId ?? id.id), source: source ?? id.source }, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/game/$source/$id', params: { id: String(sourceId ?? id.id), source: source ?? id.source } });
};
const platformUrl = new URL(`${RPC_URL(__HOST__)}${data.game.path_platform_cover}`);
@ -27,7 +24,26 @@ export default function FrontEndGameCard (data: { index: number, game: FrontEndG
previewUrl.searchParams.set('width', "640");
const badges: JSX.Element[] = [];
if (data.game.id.source === 'local')
if (data.showSource)
{
switch (data.game.id.source)
{
case "local":
badges.push(<HardDrive className="sm:size-4 md:size-8 m-1" />);
break;
case "romm":
badges.push(<img className="sm:size-4 md:size-8 m-1 rounded-full" src={`${RPC_URL(__HOST__)}/api/romm/assets/logos/romm_logo_xbox_one_square.svg`} />);
break;
case "store":
badges.push(<Store className="sm:size-4 md:size-8 m-1" />);
break;
default:
badges.push(<FileQuestion className="sm:size-4 md:size-8 m-1" />);
break;
}
} else if (data.game.id.source === 'local')
{
badges.push(<HardDrive className="sm:size-4 md:size-8 m-1" />);
}
@ -39,7 +55,9 @@ export default function FrontEndGameCard (data: { index: number, game: FrontEndG
preview={previewUrl.href}
title={data.game.name ?? ""}
subtitle={subtitle}
focusKey={FOCUS_KEYS.GAME_CARD(data.game.id.id)}
focusKey={FOCUS_KEYS.GAME_CARD(data.game.id)}
className={data.game.id.source === 'local' ? 'ring-offset-info/40 ring-offset-2' : ""}
previewClassName={data.game.id.source === 'local' ? "not-in-focused:opacity-40" : ""}
index={data.index}
id={`game-${data.game.id.source}-${data.game.id.id}`}
/>;

View file

@ -2,13 +2,12 @@ import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { GameMetaExtra, CardList } from "./CardList";
import { FrontEndGameType, FrontEndId, GameListFilterType, RPC_URL } from "@shared/constants";
import { useNavigate } from "@tanstack/react-router";
import { SaveSource } from "../scripts/spatialNavigation";
import { HardDrive } from "lucide-react";
import { FileQuestion, HardDrive, Store } from "lucide-react";
import { JSX, useContext } from "react";
import { GameCardFocusHandler } from "./CardElement";
import { useLocalSetting } from "../scripts/utils";
import { AnimatedBackgroundContext } from "../scripts/contexts";
import queries from "../scripts/queries";
import { allGamesQuery } from "@queries/romm";
export interface GameListParams
{
@ -25,7 +24,7 @@ export interface GameListParams
export function GameList (data: GameListParams)
{
const games = useSuspenseQuery(queries.romm.allGamesQuery(data.filters));
const games = useSuspenseQuery(allGamesQuery(data.filters));
const navigator = useNavigate();
const blur = useLocalSetting('backgroundBlur');
const backgroundContext = useContext(AnimatedBackgroundContext);
@ -51,8 +50,7 @@ export function GameList (data: GameListParams)
function handleDefaultSelect (g: FrontEndGameType)
{
SaveSource('details', { search: { focus: g.slug ?? `game-${g.id}` } });
navigator({ to: '/game/$source/$id', params: { id: String(g.source_id ?? g.id.id), source: g.source ?? g.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 } });
};
return (
@ -74,6 +72,7 @@ export function GameList (data: GameListParams)
{
badges.push(<HardDrive className="sm:size-4 md:size-8 md:p-1 m-1" />);
}
const previewUrl = new URL(`${RPC_URL(__HOST__)}${g.path_cover}`);
previewUrl.searchParams.delete('ts');
previewUrl.searchParams.set('width', "16");

View file

@ -24,10 +24,10 @@ import { RoundButton } from "./RoundButton";
import { useQuery } from "@tanstack/react-query";
import { getCurrentUserApiUsersMeGetOptions, statsApiStatsGetOptions } from "@clients/romm/@tanstack/react-query.gen";
import { RPC_URL } from "../../shared/constants";
import { JSX, useEffect, useRef } from "react";
import { SaveSource } from "../scripts/spatialNavigation";
import { JSX, Ref, RefObject, useEffect, useRef, useState } from "react";
import { systemApi } from "../scripts/clientApi";
import { Router } from "..";
import { useStickyDataAttr } from "../scripts/utils";
function HeaderAvatar (data: {
id: string;
@ -240,8 +240,7 @@ export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
],
action: () =>
{
SaveSource('settings');
Router.navigate({ to: '/settings/accounts', viewTransition: { types: ['zoom-in'] }, search: { focus: 'rommAddress' } });
Router.navigate({ to: '/settings/accounts', search: { focus: 'rommAddress' } });
},
status: user.data ? "status-success" : 'status-error',
type: 'secondary'
@ -284,15 +283,19 @@ export function HeaderStatusBar (data: { buttons?: HeaderButton[]; buttonElement
</div>;
}
export function HeaderUI (data: {
interface HeaderUIParams
{
buttons?: HeaderButton[];
accounts?: HeaderAccount[];
buttonElements?: JSX.Element[] | JSX.Element;
title?: JSX.Element;
preferredChildFocusKey?: string;
})
focusable?: boolean;
}
export function HeaderUI (data: HeaderUIParams)
{
const { ref, focusKey } = useFocusable({ focusKey: "header-elements", preferredChildFocusKey: data.preferredChildFocusKey });
const { ref, focusKey } = useFocusable({ focusKey: "header-elements", focusable: data.focusable, preferredChildFocusKey: data.preferredChildFocusKey });
return (
<FocusContext.Provider value={focusKey}>
<header
@ -307,3 +310,18 @@ export function HeaderUI (data: {
</FocusContext.Provider>
);
}
export function StickyHeaderUI (data: { ref: RefObject<any>; } & HeaderUIParams)
{
const [isStuck, setIsStuck] = useState(false);
const headerRef = useRef(null);
const sentinelRef = useRef(null);
useStickyDataAttr(headerRef, sentinelRef, data.ref, setIsStuck);
return <>
<div ref={sentinelRef} className="h-0" />
<div ref={headerRef} className='sticky not-mobile:data-stuck:backdrop-blur-xl transition-all top-0 px-2 p-2 not-data-stuck:bg-base-200 mobile:bg-base-300 z-15'>
<HeaderUI focusable={!isStuck} {...data} />
</div>
</>;
}

View file

@ -1,8 +1,9 @@
import { setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { FOCUS_KEYS } from "../scripts/types";
import { useIntersectionObserver } from "usehooks-ts";
import { FrontEndId } from "@/shared/constants";
export default function LoadMoreButton (data: { isFetching: boolean; lastId?: string; } & FocusParams & InteractParams)
export default function LoadMoreButton (data: { isFetching: boolean; lastId?: FrontEndId; } & FocusParams & InteractParams)
{
const handleAction = (e?: Event) =>
{

View file

@ -1,6 +1,6 @@
import { Notification, RPC_URL } from "@/shared/constants";
import { useEffect } from "react";
import toast from "react-hot-toast";
import toast, { ToastOptions } from "react-hot-toast";
export default function Notifications (data: {})
{
@ -10,15 +10,16 @@ export default function Notifications (data: {})
es.addEventListener('notification', (e) =>
{
const notification = JSON.parse(e.data) as Notification;
const options: ToastOptions = { removeDelay: notification.duration };
if (notification.type === 'error')
{
toast.error(notification.message);
toast.error(notification.message, options);
} else if (notification.type === 'success')
{
toast.success(notification.message);
toast.success(notification.message, options);
} else
{
toast.custom(notification.message);
toast.custom(notification.message, options);
}
});

View file

@ -3,7 +3,6 @@ import { useNavigate } from "@tanstack/react-router";
import { DefaultRommStaleTime, RPC_URL } from "@shared/constants";
import { CardList, GameMetaExtra } from "./CardList";
import { rommApi } from "../scripts/clientApi";
import { SaveSource } from "../scripts/spatialNavigation";
import { JSX, useMemo } from "react";
import { HardDrive } from "lucide-react";
import { GameCardFocusHandler } from "./CardElement";
@ -37,8 +36,7 @@ export function PlatformsList (data: {
const handleDefaultSelect = (source: string, id: string) =>
{
SaveSource('game-list');
navigate({ to: `/platform/${source}/${id}`, viewTransition: { types: ['zoom-in'] } });
navigate({ to: `/platform/${source}/${id}` });
};
const platformsMapped = useMemo(() => platforms.sort((a, b) => a.updated_at.getTime() - b.updated_at.getTime())

View file

@ -1,12 +1,13 @@
import { RPC_URL } from "@/shared/constants";
import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { useEffect, useRef, useState } from "react";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import FocusDots from "./FocusDots";
import { scrollIntoNearestParent, useDragScroll } from "../scripts/utils";
import { Fullscreen } from "lucide-react";
import Carousel from "./Carousel";
import { ContextDialog } from "./ContextDialog";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "../scripts/shortcuts";
import { GamePadButtonCode, useShortcuts } from "../scripts/shortcuts";
import { twMerge } from "tailwind-merge";
function Screenshot (data: { path: string; index: number; setFocused?: (index: number) => void; } & InteractParams)
{
@ -26,7 +27,43 @@ function Screenshot (data: { path: string; index: number; setFocused?: (index: n
</div>;
}
export default function Screenshots (data: { screenshots: string[]; } & FocusParams)
function Preview (data: { id: string; screenshots?: string[]; preview: number; setPreview: Dispatch<SetStateAction<number | undefined>>; })
{
const { ref, focusKey } = useFocusable({ focusKey: data.id });
useShortcuts(focusKey, () => [
{
button: GamePadButtonCode.Left,
label: "Left",
action: () =>
{
if (data.preview === undefined || !data.screenshots) return;
data.setPreview(p =>
{
if (!data.screenshots) return p;
return (data.screenshots.length + (p ?? 0) - 1) % data.screenshots.length;
});
}
},
{
button: GamePadButtonCode.Right,
label: "Right",
action: () =>
{
if (data.preview === undefined || !data.screenshots) return;
data.setPreview(p =>
{
if (!data.screenshots) return p;
return (p ?? 0 + 1) % data.screenshots.length;
});
}
}
], [data.preview, focusKey, data.screenshots?.length ?? 0]);
return <img ref={ref} draggable={false} className="object-cover w-full h-full rounded-2xl" src={`${RPC_URL(__HOST__)}${data.screenshots?.[data.preview]}`} loading="lazy" />;
}
export default function Screenshots (data: { screenshots?: string[]; className?: string; } & FocusParams)
{
const [preview, setPreview] = useState<number | undefined>(undefined);
const scrollRef = useRef<HTMLDivElement>(null);
@ -41,9 +78,10 @@ export default function Screenshots (data: { screenshots: string[]; } & FocusPar
useEffect(() =>
{
if ((focused || hasFocusedChild) && scrollRef.current)
if ((focused || hasFocusedChild) && scrollRef.current && data.screenshots)
{
const closest = findClosestElementToCenter(scrollRef.current);
if (!closest) return;
const closestIndex = Array.from(scrollRef.current.children).indexOf(closest);
setFocus(`screenshot-${closestIndex}`);
}
@ -54,6 +92,7 @@ export default function Screenshots (data: { screenshots: string[]; } & FocusPar
const center = element.scrollLeft + element.clientWidth / 2;
const children = Array.from(element.children) as HTMLElement[];
if (children.length <= 0) return undefined;
// find child closest to center
return children.reduce((closest, child) =>
@ -78,7 +117,7 @@ export default function Screenshots (data: { screenshots: string[]; } & FocusPar
const handleScroll = (dir: number, element: HTMLDivElement) =>
{
const current = findClosestElementToCenter(element);
if (!current) return;
const next = (dir > 0 ? current.nextElementSibling : current.previousElementSibling) as HTMLElement | null;
if (!next) return;
@ -89,42 +128,21 @@ export default function Screenshots (data: { screenshots: string[]; } & FocusPar
});
};
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);
return <div ref={ref} className="flex flex-col w-full z-0 min-h-0">
return <div ref={ref} className={twMerge("flex flex-col w-full z-0 min-h-0", data.className)}>
<FocusContext value={focusKey}>
<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" >
{data.screenshots.map((s, i) => <Screenshot key={s} index={i} path={s} onAction={() => setPreview(i)} />)}
{data.screenshots?.map((s, i) => <Screenshot key={s} index={i} path={s} onAction={() => setPreview(i)} />) ?? <div className="skeleton w-32 h-32"></div>}
</Carousel>
<FocusDots scrollElement={scrollRef} />
</FocusContext>
{preview !== undefined && <ContextDialog id="screenshots" close={() =>
{
setFocus(`screenshot-${preview}`);
setFocus(`screenshot-${preview}`, { instant: true });
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" />
<Preview id="screenshot-preview" screenshots={data.screenshots} preview={preview} setPreview={setPreview} />
</ContextDialog>}
</div>;
}

View file

@ -0,0 +1,50 @@
import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { JSX } from "react";
import { twMerge } from "tailwind-merge";
export interface StatEntry
{
icon?: JSX.Element,
label: string | JSX.Element,
content: string | JSX.Element | string[];
}
function Label (data: { id: string, label: string | JSX.Element; })
{
return <div className="font-semibold focused:text-accent">{data.label}:</div>;
}
export default function StatList (data: {
id: string;
stats: StatEntry[];
elementClassName?: string;
focusable?: boolean;
} & FocusParams)
{
const { ref, focusKey } = useFocusable({
focusKey: data.id,
focusable: data.focusable,
onFocus: (l, p, details) => data.onFocus?.(focusKey, ref.current, details)
});
return <ul ref={ref} className="grid md:grid-cols-[8rem_1fr] sm:px-8 md:px-16 py-4 gap-2 focused:border-y focused:border-dashed focused:border-base-content/40">
<FocusContext value={focusKey}>
{data.stats.map((s, i) =>
{
let content: any = undefined;
if (s.content instanceof Array)
{
content = <div key={`label-items-${i}`} className="flex flex-wrap gap-2">{s.content.map((c, ci) => <span key={`label-items-${i}-${ci}`} className={twMerge("rounded-full bg-base-200 px-3 py-1", data.elementClassName)}>{c}</span>)}</div>;
} else
{
content = <div key={`label-element-${i}`} className={twMerge("flex gap-2 rounded-full bg-base-200 px-3 py-1", data.elementClassName)}>{s.icon}{s.content}</div>;
}
const element = <>
<Label id={`${data.id}-label-${i}`} key={`label-${i}`} label={s.label} />
{content}
</>;
return element;
})}
</FocusContext>
</ul>;
}

View file

@ -0,0 +1,35 @@
import { FrontEndGameTypeDetailed, FrontEndGameTypeDetailedAchievement } from "@/shared/constants";
import { useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { Medal } from "lucide-react";
function Achievement (data: { index: number, achievement: FrontEndGameTypeDetailedAchievement; } & FocusParams)
{
const { ref, focusKey } = useFocusable({ focusKey: `achievement-${data.index}`, onFocus: (l, p, details) => data.onFocus?.(focusKey, ref.current, details) });
return <div ref={ref} className="flex focusable focusable-primary gap-4 p-4 bg-base-300 rounded-3xl items-center scroll-mb-16 scroll-mt-32">
<div data-unlocked={!!data.achievement.date} data-hardcore={!!data.achievement.date_hardcode} className="data-[unlocked=true]:ring-4 aspect-square data-[unlocked=true]:ring-offset-4 ring-accent ring-offset-warning rounded-2xl overflow-hidden">
<img className="scale-110" src={data.achievement.badge_url} />
</div>
<div className="flex gap-2 sm:flex-col md:flex-row grow justify-between sm:items-start md:items-center">
<div>
<div className="flex gap-2">
{data.achievement.type === 'win_condition' && <Medal />}
<p className="font-semibold">{data.achievement.title}</p>
</div>
<p className="text-base-content/60">{data.achievement.description}</p>
</div>
{!!data.achievement.date && <div className="bg-base-100 rounded-3xl px-4 p-1">{data.achievement.date.toDateString()}</div>}
</div>
</div>;
}
export default function Achievements (data: { game: FrontEndGameTypeDetailed; })
{
const handleFocus = (key: string, node: HTMLElement, details: any) =>
{
node.scrollIntoView({ behavior: details?.instant ? 'instant' : 'smooth', block: 'nearest' });
};
return <div className="grid sm:grid-cols-1 md:grid-cols-3 px-4 gap-2">
{data.game.achievements?.entires.map((a, i) => <Achievement index={i} onFocus={handleFocus} key={i} achievement={a} />)}
</div>;
}

View file

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

View file

@ -8,7 +8,7 @@ import { FileSearchCorner, FolderSearch, Pen, Save } from "lucide-react";
import { ContextDialog } from "../ContextDialog";
import FilePicker from "../FilePicker";
import { setFocus } from "@noriginmedia/norigin-spatial-navigation";
import queries from "@/mainview/scripts/queries";
import { getSettingQuery, setSettingMutation } from "@queries/settings";
type KeysWithValueAssignableTo<T, Value> = {
[K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never;
@ -33,7 +33,7 @@ export function PathSettingsOption (data: PathSettingsOptionParams)
const [localValue, setLocalValue] = useState<string | undefined>();
const [dirty, setDirty] = useState(false);
const setMutation = useMutation({
...queries.settings.setSettingMutation(data.id),
...setSettingMutation(data.id),
onSuccess: (d, v, r, cx) =>
{
setDirty(r !== localValue);
@ -63,7 +63,7 @@ export function PathSettingsOptionBase (data: PathSettingsOptionParams & {
})
{
const [isBrowsing, setIsBrowsing] = useState(false);
const { data: defaultValue } = useQuery(queries.settings.getSettingQuery(data.id));
const { data: defaultValue } = useQuery(getSettingQuery(data.id));
const changed = defaultValue !== data.localValue;
useEffect(() =>

View file

@ -3,7 +3,7 @@ import { SettingsType } from "../../../shared/constants";
import { useMutation, useQuery } from "@tanstack/react-query";
import { OptionSpace } from "./OptionSpace";
import { OptionInput } from "./OptionInput";
import queries from "@/mainview/scripts/queries";
import { getSettingQuery, setSettingMutation } from "@queries/settings";
type KeysWithValueAssignableTo<T, Value> = {
[K in keyof T]: Exclude<T[K], undefined> extends Value ? K : never;
@ -20,8 +20,8 @@ export function SettingsOption (data: {
{
const [dirty, setDirty] = useState(false);
const [localValue, setLocalValue] = useState<string | undefined>();
useQuery(queries.settings.getSettingQuery(data.id));
const setMutation = useMutation(queries.settings.setSettingMutation(data.id));
useQuery(getSettingQuery(data.id));
const setMutation = useMutation(setSettingMutation(data.id));
const handleSave = useCallback(() =>
{

View file

@ -69,7 +69,7 @@ export function EmulatorsSection (data: {
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', viewTransition: { types: ['zoom-in'] } })} onFocus={({ node, instant }) => scrollIntoNearestParent(node, { behavior: instant ? 'instant' : 'smooth' })} />
</Carousel>
</section>

View file

@ -1,50 +1,58 @@
import { useRef } from "react";
import { CSSProperties, Ref, RefObject, useEffect, useRef } from "react";
import
{
useFocusable,
FocusContext,
} from "@noriginmedia/norigin-spatial-navigation";
import { Gamepad2, Star } from "lucide-react";
import { useDragScroll } from "@/mainview/scripts/utils";
import { scrollIntoNearestParent, useDragScroll } from "@/mainview/scripts/utils";
import FocusDots from "../FocusDots";
import { FrontEndGameType, FrontEndId } from "@/shared/constants";
import FrontEndGameCard from "../FrontEndGameCard";
import { FOCUS_KEYS } from "@/mainview/scripts/types";
import Carousel from "../Carousel";
import { twMerge } from "tailwind-merge";
export function GamesSection ({ games, onSelect, onFocus }: {
export function GamesSection (data: {
games?: FrontEndGameType[];
onSelect?: (id: FrontEndId, focusKey: string) => void;
className?: string;
showSources?: boolean;
ref?: Ref<any>;
} & FocusParams)
{
const { ref, focusKey } = useFocusable({
const { ref, focusKey, focused, focusSelf } = useFocusable({
focusKey: FOCUS_KEYS.GAME_SECTION,
trackChildren: true,
onFocus: (_l, _p, details) => onFocus?.(focusKey, ref.current, details)
onFocus: (_l, _p, details) => data.onFocus?.(focusKey, ref.current, details)
});
const containerRef = useRef(null);
useDragScroll(containerRef);
useEffect(() =>
{
if (focused)
focusSelf();
}, [!!data.games]);
return (
<FocusContext.Provider value={focusKey}>
<section ref={ref} className="px-6 py-3 select-none">
<div className="flex items-center gap-3 mb-4">
<div className="w-2 h-5 rounded-full bg-accent shadow-sm shadow-error/40" />
<Gamepad2 className="text-accent" />
<h2 className="font-bold uppercase tracking-widest text-accent grow">
Featured Games
</h2>
<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>
<section ref={(r) =>
{
ref.current = r;
if (data.ref instanceof Function) data.ref(r);
else if (data.ref) data.ref.current = r;
}} className={twMerge("select-none", data.className)}>
<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
{data.games?.map((g, i) => <FrontEndGameCard
showSource={data.showSources}
key={g.id.id}
game={g}
onAction={() => onSelect?.(g.id, FOCUS_KEYS.GAME_CARD(g.id.id))}
onAction={() => data.onSelect?.(g.id, FOCUS_KEYS.GAME_CARD(g.id))}
onFocus={(key, node, details) => scrollIntoNearestParent(node, { behavior: details.instant ? 'instant' : 'smooth' })}
index={i} />) ?? Array.from({ length: 8 }).map((_, i) => <div key={i} className="skeleton h-38 w-full" />)}
</Carousel>
</section>
<FocusDots elements={games?.map(e => FOCUS_KEYS.GAME_CARD(e.id.id)) ?? []} />
<FocusDots elements={data.games?.map(e => FOCUS_KEYS.GAME_CARD(e.id)) ?? []} />
</FocusContext.Provider>
);
}

View file

@ -1,5 +1,6 @@
import queries from "@/mainview/scripts/queries";
import { storeGetStatsQuery } from "@queries/store";
import { useQuery } from "@tanstack/react-query";
import { Joystick, LibraryBig, Save, TriangleAlert } from "lucide-react";
@ -15,7 +16,7 @@ export function StatsSection ({
}: StatsSectionProps)
{
const { data: stats } = useQuery(queries.store.storeGetStatsQuery);
const { data: stats } = useQuery(storeGetStatsQuery);
return (
<section className="px-6 pt-3 pb-4">

View file

@ -5,8 +5,18 @@ import { Button } from "../options/Button";
import useActiveControl from "@/mainview/scripts/gamepads";
import { useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts";
import { ChevronRight, EllipsisVertical, HardDrive } from "lucide-react";
import { ChevronRight, EllipsisVertical, FileQuestion, IceCream2, Package, Store } from "lucide-react";
import { FOCUS_KEYS } from "@/mainview/scripts/types";
import { FlatpackIcon } from "@/mainview/scripts/brandIcons";
import { JSX } from "react";
export const emulatorStatusIcons: Record<string, JSX.Element> = {
store: <Store />,
custom: <FileQuestion />,
flatpak: FlatpackIcon,
winget: <Package />,
scoop: <IceCream2 />
};
export function StoreEmulatorCard (data: {
id: string;
@ -35,7 +45,7 @@ export function StoreEmulatorCard (data: {
ref={ref}
role="button"
tabIndex={0}
data-installed={data.emulator.exists ? true : undefined}
data-installed={!!data.emulator.validSource}
onClick={isTouch ? handleSelect : undefined}
className={twMerge("relative focusable focusable-info bg-base-100 rounded-4xl transition-shadow focused:not-control-mouse:animate-scale-small shadow-lg border border-base-content/10 active:ring-4 active:ring-base-content active:transition-none", data.className)}
>
@ -44,14 +54,14 @@ export function StoreEmulatorCard (data: {
<div className="flex gap-2">
<div className="flex items-start">
<div
data-installed={data.emulator.exists}
data-installed={!!data.emulator.validSource}
className={`size-14 p-2 rounded-full bg-info flex items-center justify-center text-xl shadow-lg data-[installed=true]:bg-success`}
>
<img draggable={false} src={data.emulator.logo}></img>
</div>
</div>
<div>
<p data-installed={data.emulator.exists} className="font-bold text-base-content text-xl leading-snug data-[installed=true]:text-success">{data.emulator.name}</p>
<p data-installed={!!data.emulator.validSource} className="font-bold text-base-content text-xl leading-snug data-[installed=true]:text-success">{data.emulator.name}</p>
<ul className="flex flex-wrap gap-1">
{data.emulator.systems.map(({ id, name, icon }) =>
{
@ -66,10 +76,12 @@ export function StoreEmulatorCard (data: {
</div>
<div className="flex gap-0.5 mt-1 h-10 items-center">
{data.emulator.exists && <div className="tooltip" data-tip="Installed">
<div className="flex items-center justify-center rounded-full p-1 size-8 bg-success text-success-content"><HardDrive /></div>
{!!data.emulator.validSource && <div className="tooltip" data-tip={data.emulator.validSource.type}>
<div className="flex items-center justify-center rounded-full p-1 size-8 bg-success text-success-content">
{emulatorStatusIcons[data.emulator.validSource?.type ?? '']}
</div>
</div>}
{<div className="tooltip" data-tip="Game Count">
{data.emulator.gameCount > 0 && <div className="tooltip" data-tip="Game Count">
<div className="flex items-center justify-center rounded-full font-semibold size-9 p-2 bg-base-200 text-base-content/40">{data.emulator.gameCount}</div>
</div>}
{isMouse && <>

View file

@ -28,6 +28,7 @@ window.addEventListener('message', (e) =>
});
window.EJS_threads = true;
window.EJS_player = "#game";
window.EJS_lightgun = false;
window.EJS_startOnLoaded = true;

View file

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

View file

@ -393,6 +393,17 @@ body {
width: 100%;
}
html:active-view-transition-type(slide-up) {
&::view-transition-old(root) {
animation: fade-out 300ms ease-in forwards;
}
&::view-transition-new(root) {
animation: slide-up 300ms ease-in-out forwards;
}
}
html:active-view-transition-type(zoom-in) {
&::view-transition-old(root) {
@ -449,6 +460,18 @@ body {
}
}
@keyframes slide-up {
from {
transform: translateY(10vh);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
@keyframes zoom-in-fade-in {
from {
scale: 105%;

View file

@ -17,6 +17,7 @@ import "./scripts/spatialNavigation";
import NotFound from "./components/NotFound";
import Error from "./components/Error";
import serviceWorker from './scripts/serviceWorker?worker&url';
import { getCurrentFocusKey, setFocus } from "@noriginmedia/norigin-spatial-navigation";
if ('serviceWorker' in navigator)
{
@ -44,10 +45,42 @@ export const Router = createRouter({
history: hashHistory,
defaultPreload: "intent",
context: { queryClient },
scrollRestoration: false,
scrollRestoration: true,
defaultNotFoundComponent: NotFound,
defaultPendingMs: 300,
defaultErrorComponent: Error
defaultErrorComponent: Error,
defaultViewTransition: {
types ({ fromLocation, toLocation })
{
let direction = 'in';
if (fromLocation)
{
const fromIndex = fromLocation.state.__TSR_index;
const toIndex = toLocation.state.__TSR_index;
direction = fromIndex > toIndex ? 'in' : 'out';
}
return [`zoom-${direction}`];
},
}
});
const focusMap = new Map<number, string>();
Router.history.subscribe((op) =>
{
if (op.action.type === 'PUSH')
{
focusMap.set(op.location.state.__TSR_index - 1, getCurrentFocusKey());
} else if (op.action.type === 'BACK')
{
if (focusMap.has(op.location.state.__TSR_index))
{
setFocus(focusMap.get(op.location.state.__TSR_index)!);
focusMap.delete(op.location.state.__TSR_index);
}
}
});
// Register things for typesafety

View file

@ -5,7 +5,7 @@ import { DefaultRommStaleTime } from '@shared/constants';
import { useQuery } from '@tanstack/react-query';
import { useContext } from 'react';
import { AnimatedBackgroundContext } from '../scripts/contexts';
import queries from '../scripts/queries';
import { getCollectionQuery } from '@queries/romm';
export const Route = createFileRoute('/collection/$id')({
component: RouteComponent,
@ -18,7 +18,7 @@ export const Route = createFileRoute('/collection/$id')({
function RouteComponent ()
{
const { id } = Route.useParams();
const { data: collection } = useQuery(queries.romm.getCollectionQuery(Number(id)));
const { data: collection } = useQuery(getCollectionQuery(Number(id)));
const animatedBgContext = useContext(AnimatedBackgroundContext);
return (

View file

@ -14,13 +14,13 @@ import useActiveControl from '../scripts/gamepads';
import { twMerge } from 'tailwind-merge';
import { HeaderAccounts, HeaderStatusBar } from '../components/Header';
import { RoundButton } from '../components/RoundButton';
import queries from '../scripts/queries';
import { gameQuery } from '@queries/romm';
export const Route = createFileRoute('/embedded/$source/$id')({
component: RouteComponent,
loader: async (ctx) =>
{
const data = await ctx.context.queryClient.fetchQuery(queries.romm.gameQuery(ctx.params.source, ctx.params.id));
const data = await ctx.context.queryClient.fetchQuery(gameQuery(ctx.params.source, ctx.params.id));
return { data };
},
validateSearch: zodValidator(z.record(z.string(), z.string().optional().nullable()))
@ -133,7 +133,7 @@ function RouteComponent ()
function HandleGoBack ()
{
Router.navigate({ to: '/game/$source/$id', viewTransition: { types: ['zoom-out'] }, params: { source, id } });
Router.navigate({ to: '/game/$source/$id', params: { source, id }, replace: true });
}
useEventListener('message', e =>

View file

@ -1,37 +1,53 @@
import { createFileRoute, ErrorComponentProps } from "@tanstack/react-router";
import { CommandEntry, FrontEndGameTypeDetailed, GameInstallProgress, GameStatusType, RPC_URL } from "@shared/constants";
import { CommandEntry, RPC_URL } from "@shared/constants";
import { twMerge } from "tailwind-merge";
import { JSX, RefObject, useEffect, useRef, useState } from "react";
import { FocusContext, setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import classNames from "classnames";
import { Clock, CloudDownload, Download, HardDrive, Image, PackageOpen, Play, Settings, Store, Trash, TriangleAlert, Trophy } from "lucide-react";
import { Calendar, Clock, CloudDownload, Download, EllipsisVertical, Folder, Gamepad2, HardDrive, Image, Info, PackageOpen, Play, Settings, Store, Trash, TriangleAlert, Trophy } from "lucide-react";
import { HeaderUI } from "../../components/Header";
import prettyBytes from 'pretty-bytes';
import { PopSource, SaveSource, useFocusEventListener } from "../../scripts/spatialNavigation";
import { useFocusEventListener } from "../../scripts/spatialNavigation";
import { AnimatedBackground } from "../../components/AnimatedBackground";
import { rommApi } from "../../scripts/clientApi";
import toast from "react-hot-toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Router } from "../..";
import { ContextDialog, ContextList, DialogEntry } from "../../components/ContextDialog";
import { ContextDialog, ContextList, DialogEntry, useContextDialog } from "../../components/ContextDialog";
import Shortcuts from "../../components/Shortcuts";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "@/mainview/scripts/shortcuts";
import queries from "@/mainview/scripts/queries";
import Screenshots from "@/mainview/components/Screenshots";
import { useStickyDataAttr } from "@/mainview/scripts/utils";
import { HandleGoBack, scrollIntoViewHandler, useStickyDataAttr } from "@/mainview/scripts/utils";
import useActiveControl from "@/mainview/scripts/gamepads";
import { FilterUI } from "@/mainview/components/Filters";
import StatList, { StatEntry } from "@/mainview/components/StatList";
import { useIntersectionObserver, useLocalStorage } from "usehooks-ts";
import { EmulatorsSection } from "@/mainview/components/store/EmulatorsSection";
import { zodValidator } from "@tanstack/zod-adapter";
import z from "zod";
import Achievements from "@/mainview/components/game/Achievements";
import { getErrorMessage } from "react-error-boundary";
import { GameDetailsContext } from "@/mainview/scripts/contexts";
import { rommApi } from "@/mainview/scripts/clientApi";
import { deleteGameMutation, gameQuery, gamesRecommendedBasedOnGameQuery, installMutation, playMutation } from "@queries/romm";
import { GamesSection } from "@/mainview/components/store/GamesSection";
export const Route = createFileRoute("/game/$source/$id")({
loader: async ({ params, context }) =>
{
const data = await context.queryClient.fetchQuery(queries.romm.gameQuery(params.source, params.id));
const data = await context.queryClient.fetchQuery(gameQuery(params.source, params.id));
return { data };
},
component: GameDetailsUI,
pendingComponent: GameDetailsUIPending,
errorComponent: Error
errorComponent: Error,
validateSearch: zodValidator(z.object({ focus: z.string().optional() }))
});
function useDetailsSection ()
{
return useLocalStorage('details-section', 'screenshots');
}
function Error (data: ErrorComponentProps)
{
const { ref, focusKey, focusSelf } = useFocusable({ focusKey: "game-details-error", preferredChildFocusKey: "main-details" });
@ -51,7 +67,7 @@ function Error (data: ErrorComponentProps)
<HeaderUI />
</div>
<div className="absolute w-full flex flex-col justify-center items-center h-full overflow-hidden bg-linear-to-t from-base-100 to-base-100/40">
<div className="flex gap-2 items-center text-4xl text-error"><TriangleAlert className="size-12" /> {data.error.message}</div>
<div className="flex gap-2 items-center text-4xl text-error"><TriangleAlert className="size-12" /> {JSON.stringify(data.error, null, 3)}</div>
</div>
<div className="bg-base-200">
@ -139,35 +155,52 @@ function GameDetailsUIPending ()
</AnimatedBackground>;
}
function HandleGoBack ()
function MoreDetails (data: {})
{
const { to, search } = PopSource('details');
Router.navigate({ to: to ?? '/', viewTransition: { types: ['zoom-out'] }, search });
const { data: game } = Route.useLoaderData();
const [details] = useDetailsSection();
const { ref, focusKey, hasFocusedChild } = useFocusable({
focusKey: "game-more-details-section",
onFocus: (l, p, d) => scrollIntoViewHandler({ block: 'start', behavior: 'smooth' })(focusKey, ref.current, d),
trackChildren: true
});
return <div ref={ref} className="scroll-mt-[15vh]">
<FocusContext value={focusKey}>
<Divider rootFocusKey={focusKey} showShortcuts={hasFocusedChild} />
<div className="bg-base-200 py-12 min-h-[80vh]">
<div key={details} className="h-full animate-slide-up">
{details === 'screenshots' && <div className="h-[60vh]"><Screenshots screenshots={game.paths_screenshots} /></div>}
{details === 'stats' && <Stats />}
{details === 'achievements' && <Achievements game={game} />}
</div>
</div>
</FocusContext>
</div>;
}
function Details (data: { mainAreaRef: RefObject<HTMLDivElement | null>, game?: FrontEndGameTypeDetailed; })
function Details (data: { mainAreaRef: RefObject<HTMLDivElement | null>; })
{
const { data: game } = Route.useLoaderData();
const { ref, focusKey } = useFocusable({
focusKey: 'main-details', onFocus: () =>
{
data.mainAreaRef.current?.scrollIntoView({ block: 'end', behavior: 'smooth' });
},
focusKey: 'main-details',
onFocus: (l, p, d) => scrollIntoViewHandler({ block: 'end', behavior: 'smooth' })(focusKey, ref.current, d),
preferredChildFocusKey: "play-btn",
saveLastFocusedChild: false
});
const platformCoverImg = new URL(`${RPC_URL(__HOST__)}${data.game?.path_platform_cover ?? ''}`);
const platformCoverImg = new URL(`${RPC_URL(__HOST__)}${game?.path_platform_cover ?? ''}`);
platformCoverImg.searchParams.set("width", "64");
const gameCoverImg = data.game?.path_cover ? `${RPC_URL(__HOST__)}${data.game?.path_cover}` : undefined;
const gameCoverImg = game?.path_cover ? `${RPC_URL(__HOST__)}${game?.path_cover}` : undefined;
let fileSizeIcon: JSX.Element | undefined;
if (!data.game)
if (!game)
{
fileSizeIcon = <span className="loading loading-spinner loading-lg"></span>;
} else if (data.game.missing)
} else if (game.missing)
{
fileSizeIcon = <TriangleAlert />;
} else if (data.game.local)
} else if (game.local)
{
fileSizeIcon = <HardDrive />;
} else
@ -186,23 +219,23 @@ function Details (data: { mainAreaRef: RefObject<HTMLDivElement | null>, game?:
</div>
<div className="flex-2 flex flex-col sm:gap-1 md:gap-6 sm:pt-2 md:pt-16 min-h-0">
<div className="flex flex-wrap sm:gap-4 md:gap-6 shrink-0">
<Detail icon={<Clock />} >{data.game?.last_played ? new Date(data.game.last_played).toDateString() : "Never"}</Detail>
{!!data.game && (data.game.fs_size_bytes !== null || data.game.missing) &&
<div className={classNames({ "text-error": data.game.missing })}>
<div className="tooltip" data-tip={data.game.path_fs}>
<Detail icon={fileSizeIcon} >{data.game.missing ? 'Missing' : prettyBytes(data.game.fs_size_bytes!)}</Detail>
<Detail icon={<Clock />} >{game?.last_played ? new Date(game.last_played).toDateString() : "Never"}</Detail>
{!!game && (game.fs_size_bytes !== null || game.missing) &&
<div className={classNames({ "text-error": game.missing })}>
<div className="tooltip" data-tip={game.path_fs}>
<Detail icon={fileSizeIcon} >{game.missing ? 'Missing' : prettyBytes(game.fs_size_bytes!)}</Detail>
</div>
</div>}
<Detail icon={<img className="size-6" src={platformCoverImg.href}></img>} >{data.game?.platform_display_name ?? <div className="skeleton h-4 w-32"></div>}</Detail>
<Detail icon={<img className="size-6" src={platformCoverImg.href}></img>} >{game?.platform_display_name ?? <div className="skeleton h-4 w-32"></div>}</Detail>
<Detail icon={
<Store />
} >
{data.game?.source ?? data.game?.id.source}
{data.game?.local && <small className="text-base-content/60 font-semibold">local</small>}</Detail>
{game?.source ?? game?.id.source}
{game?.local && <small className="text-base-content/60 font-semibold">local</small>}</Detail>
</div>
<div className="md:hidden divider divider-vertical m-0"></div>
<div className="text-base-content/80 flex-1 min-h-0 leading-relaxed grow text-wrap whitespace-break-spaces text-ellipsis overflow-hidden text-lg">
{data.game?.summary ?? <div className="flex flex-col gap-4 w-full">
{game?.summary ?? <div className="flex flex-col gap-4 w-full">
<div className="skeleton h-4 w-[30%]"></div>
<div className="skeleton h-4 w-[80%]"></div>
<div className="skeleton h-4 w-full"></div>
@ -211,107 +244,90 @@ function Details (data: { mainAreaRef: RefObject<HTMLDivElement | null>, game?:
<div className="skeleton h-4 w-[80%]"></div>
</div>}
</div>
{!!data.game && <ActionButtons key="actions" game={data.game} />}
{!!game && <ActionButtons key="actions" />}
</div>
</section>
</FocusContext>
</main>;
}
function AchievementsInfo (data: { game: FrontEndGameTypeDetailed; })
function AchievementsInfo (data: InteractParams)
{
if (!data.game.achievements)
const { data: game } = Route.useLoaderData();
if (!game.achievements)
{
return false;
}
return <ActionButton key="achievements" square tooltip="Achievements" type="base" id="achievements" >
<div className="flex flex-col gap-2 items-center text-2xl">
<div className="flex flex-row">
return <ActionButton key="achievements" square tooltip="Achievements" type="base" className="sm:rounded-2xl md:rounded-3xl" id="achievements" onAction={data.onAction} >
<div className="flex flex-col sm:gap-0 md:gap-2 items-center sm:text-xl md:text-2xl sm:px-4 sm:py-2 md:p-0">
<div className="flex flex-row items-center gap-1">
<Trophy />
{`${data.game.achievements.unlocked}/${data.game.achievements.total}`}
{`${game.achievements.unlocked}/${game.achievements.total}`}
</div>
<progress className="progress progress-secondary w-full" value={50} max="100"></progress>
<progress className="progress progress-secondary w-full" value={game.achievements.unlocked / game.achievements.total} max="1"></progress>
</div>
</ActionButton>;
}
function MainActions (data: { game: FrontEndGameTypeDetailed; })
function MainActions ()
{
const { data } = Route.useLoaderData();
const { source, id } = Route.useParams();
const installMutation = useMutation({
mutationKey: ['install'],
mutationFn: async () =>
const installMut = useMutation(installMutation(source, id));
const playMut = useMutation({
...playMutation, onError (error)
{
const { error } = await rommApi.api.romm.game({ source: data.game.id.source })({ id: data.game.id.id }).install.post();
if (error) throw error;
}
});
const playMutation = useMutation({
mutationKey: ['play'],
mutationFn: async () =>
{
const { error } = await rommApi.api.romm.game({ source: data.game.id.source })({ id: data.game.id.id }).play.post();
if (error)
{
if (error.value.message)
{
toast.error(error.value.message);
}
throw error;
};
}
toast.error(error.message);
},
});
const ws = useRef<{ send: (data: string) => void; }>(undefined);
const [progress, setProgress] = useState<number | undefined>(undefined);
const [status, setStatus] = useState<GameStatusType | undefined>(undefined);
const [status, setStatus] = useState<string | undefined>(undefined);
const [error, setError] = useState<string | undefined>(undefined);
const [details, setDetails] = useState<string | undefined>(undefined);
const [commands, setCommands] = useState<CommandEntry[] | undefined>(undefined);
const [preferredCommand, setPreferredCommand] = useLocalStorage<string | number | undefined>(`${data.source ?? data.id.source}-${data.source_id ?? data.id.id}-preferred-command`, undefined);
const queryClient = useQueryClient();
const validCommands = commands ? commands.filter(c => c.valid) : [];
const validDefaultCommand = commands?.find(c =>
{
if (!c.valid) return false;
if (preferredCommand && c.id !== preferredCommand) return false;
return true;
});
useEffect(() =>
{
const es = new EventSource(`${RPC_URL(__HOST__)}/api/romm/status/${data.game.id.source}/${data.game.id.id}`);
const sub = rommApi.api.romm.status({ source: data.id.source })({ id: data.id.id }).subscribe();
ws.current = sub.ws;
es.onmessage = ({ data }) =>
sub.subscribe((e) =>
{
const stats = JSON.parse(data) as GameInstallProgress;
setProgress(stats.progress);
setStatus(stats.status);
setDetails(stats.details);
setCommands(stats.commands);
setError(stats.error);
};
setStatus(e.data.status);
setProgress((e.data as any).progress);
setDetails((e.data as any).details);
setCommands((e.data as any).commands);
es.addEventListener('refresh', () =>
{
queryClient.invalidateQueries({ queryKey: ['game', data.game.id] });
Router.navigate({ to: '/game/$source/$id', params: { id, source } });
});
es.addEventListener('error', (e) =>
{
if ((e as any).data)
if (e.data.status === 'refresh')
{
const stats = JSON.parse((e as any).data) as GameInstallProgress;
toast.error(stats.error);
setError(stats.error);
queryClient.invalidateQueries({ queryKey: ['game', data.id] });
Router.navigate({ to: '/game/$source/$id', params: { id, source }, replace: true });
} else if (e.data.status === 'error')
{
const errorMessage = getErrorMessage(e.data.error);
if (!errorMessage) return;
toast.error(errorMessage);
setError(errorMessage);
}
});
es.onerror = (event) =>
return () =>
{
const error = (event as any).data?.error;
if (error)
{
toast.error(error);
setError(error);
}
sub.close();
ws.current = undefined;
};
return () => es.close();
}, [data.game.id]);
}, [data.id]);
let progressIcon: JSX.Element | undefined = undefined;
switch (status)
@ -319,29 +335,51 @@ function MainActions (data: { game: FrontEndGameTypeDetailed; })
case 'download':
progressIcon = <Download />;
break;
case 'queued':
progressIcon = <Clock />;
break;
case 'extract':
progressIcon = <PackageOpen />;
break;
}
let mainButton: JSX.Element | undefined = undefined;
const showProgress = progress !== null && !!progressIcon;
useEffect(() =>
{
if (showProgress) return;
showInstallOptions(false);
}, [showProgress]);
const handlePlay = (cmd?: CommandEntry) =>
{
if (!cmd) return;
if (cmd.emulator === 'EMULATORJS')
{
const params = new URLSearchParams(cmd.command);
Router.navigate({ to: '/embedded/$source/$id', params: { source, id }, search: Object.fromEntries(params.entries()), replace: true });
} else
{
playMut.mutate({ source: data.id.source, id: data.id.id, command_id: cmd.id });
Router.navigate({ to: '/launcher/$source/$id', params: { source, id }, replace: true });
}
};
let mainButton: any | undefined = undefined;
if (status === 'installed')
{
mainButton = <ActionButton onAction={() =>
{
const firstValid = commands?.find(c => c.valid);
if (firstValid?.emulator === 'emulatorjs')
{
const params = new URLSearchParams(firstValid.command);
Router.navigate({ to: '/embedded/$source/$id', viewTransition: { types: ['zoom-in'] }, params: { source, id }, search: Object.fromEntries(params.entries()) });
} else
{
playMutation.mutate();
SaveSource('launch');
Router.navigate({ to: '/launcher/$source/$id', viewTransition: { types: ['zoom-in'] }, params: { source, id } });
}
mainButton = <div className="flex gap-2"><ActionButton onAction={() => handlePlay(validDefaultCommand)} tooltip={validDefaultCommand?.label ?? details}
key="primary"
type='primary'
id="mainAction"
>
<Play />
}} tooltip={details} key="primary" type='primary' id="mainAction"><Play /></ActionButton>;
</ActionButton>
{validCommands.length > 1 &&
<ActionButton className="size-11! header-icon-small" tooltip={"All Commands"} type="base" id="allActionsBtn" onAction={() => showAllCommands(true, 'allActionsBtn')}>
<EllipsisVertical />
</ActionButton>}</div>;
}
else if (error)
{
@ -354,8 +392,7 @@ function MainActions (data: { game: FrontEndGameTypeDetailed; })
{
if (status === 'missing-emulator')
{
SaveSource('settings');
Router.navigate({ to: '/settings/directories', viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/settings/directories' });
}
}}
id="mainAction">
@ -366,12 +403,12 @@ function MainActions (data: { game: FrontEndGameTypeDetailed; })
{
mainButton = <ActionButton
key={status ?? 'unknown'}
disabled={installMutation.isPending}
disabled={installMut.isPending}
onAction={() =>
{
if (status === 'install')
{
installMutation.mutate();
installMut.mutate();
}
}}
tooltip={details ?? status}
@ -381,10 +418,41 @@ function MainActions (data: { game: FrontEndGameTypeDetailed; })
</ActionButton>;
}
const { dialog: allCommandDialog, setOpen: showAllCommands } = useContextDialog('all-commands-dialog', {
content: <ContextList options={validCommands.map(c =>
{
const commands: DialogEntry = {
id: String(c.id),
content: c.label ?? "",
type: 'primary',
action (ctx)
{
setPreferredCommand(c.id);
handlePlay(c);
},
};
return commands;
})} />,
preferredChildFocusKey: String(preferredCommand)
});
const { dialog: installOptionsDialog, setOpen: showInstallOptions } = useContextDialog('install-options-dialog', {
content: <ContextList options={[{
id: 'cancel',
content: "Cancel",
action (ctx)
{
ws.current?.send('cancel');
ctx.close();
},
type: 'primary'
}]} />
});
return <div className="flex gap-2">
{mainButton}
<div className="divider divider-horizontal m-0"></div>
{progress !== null && !!progressIcon && <ActionButton key="progress" square tooltip={details} type="base" id="progress" >
{showProgress && <ActionButton onAction={() => showInstallOptions(true, "progress")} key="progress" square tooltip={details} type="base" id="progress" >
<div key={`install-${status}`} data-tooltip={details ?? status} className="flex flex-col gap-2 w-16 items-center text-2xl">
<div className="flex flex-row">
{progressIcon}
@ -392,26 +460,34 @@ function MainActions (data: { game: FrontEndGameTypeDetailed; })
<progress className="progress progress-secondary w-full" value={progress} max="100"></progress>
</div>
</ActionButton>}
{installOptionsDialog}
{allCommandDialog}
</div>;
}
function ActionButtons (data: { game: FrontEndGameTypeDetailed; })
function ActionButtons (data: {})
{
const [, setDetailsSection] = useDetailsSection();
const { data: game } = Route.useLoaderData();
const [hoverText, setHoverText] = useState<string | undefined>(undefined);
const [hoverTextType, setHoverTextType] = useState<string>('accent');
const { ref, focusKey } = useFocusable({ focusKey: 'actions', onBlur: () => setHoverText(undefined) });
const [open, setOpen] = useState(false);
const deleteMutation = useMutation({
...queries.romm.deleteGameMutation,
...deleteGameMutation(game.id),
onSuccess: () =>
{
location.reload();
console.log("Deleted");
},
onError (error)
{
toast.error(getErrorMessage(error) ?? "Error While Deleting");
}
});
const contextOptions: DialogEntry[] = [];
if (data.game.local)
if (game.local)
{
contextOptions.push({
id: 'delete',
@ -451,16 +527,20 @@ function ActionButtons (data: { game: FrontEndGameTypeDetailed; })
return <div ref={ref} className="flex sm:gap-2 md:gap-4 sm:h-16 md:h-32 overflow-hidden p-2 items-center shrink-0">
<FocusContext value={focusKey}>
<MainActions game={data.game} />
<AchievementsInfo game={data.game} />
<MainActions />
<AchievementsInfo onAction={() =>
{
setDetailsSection("achievements");
if (game.achievements?.entires[0])
{
setFocus(game.achievements.entires[0].id);
}
}} />
<ActionButton tooltip="Settings" onAction={() => setOpen(true)} type="base" id="settings" icon={<Settings />} >
</ActionButton >
<ContextDialog id="settings-context" open={open} close={() =>
{
setOpen(false);
setFocus("settings");
}}>
<ContextDialog sourceFocusKey="settings" id="settings-context" open={open} close={setOpen}>
<ContextList options={contextOptions} />
</ContextDialog>
{!!hoverText && !isPointer && <p className={twMerge("flex sm:hidden md:inline py-1 md:py-2 md:px-4 rounded-4xl text-wrap wrap-anywhere text-base", (tooltipStyles as any)[hoverTextType])}>{hoverText}</p>}
@ -496,7 +576,7 @@ function ActionButton (data: {
const styles = {
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",
accent: "bg-primary text-primary-content focusable focusable-primary focusable:bg-base-content focusable:text-base-300",
accent: "bg-accent text-accent-content focusable focusable-primary focusable:bg-base-content focusable:text-base-300",
error: "bg-error text-error-content focused:bg-error focused:text-error-content",
};
return (
@ -516,45 +596,135 @@ function ActionButton (data: {
);
}
export default function GameDetailsUI ()
function Stats ()
{
const { data } = Route.useLoaderData();
const stats: StatEntry[] = [];
if (data.path_fs)
stats.push({ label: "Location", content: data.path_fs, icon: <Folder /> });
if (data.companies)
stats.push({ label: "Companies", content: data.companies });
if (data.genres)
stats.push({ label: 'Genres', content: data.genres });
if (data.release_date)
stats.push({ label: "Release Date", content: data.release_date.toLocaleDateString(), icon: <Calendar /> });
if (data.emulators)
stats.push({ label: "Emulators", content: data.emulators.map(e => e.name) });
return <StatList elementClassName="bg-base-300" stats={stats} />;
}
function Divider (data: { rootFocusKey: string; showShortcuts: boolean; })
{
const [details, setDetails] = useDetailsSection();
const { data: game } = Route.useLoaderData();
const { ref, focusKey } = useFocusable({
focusKey: "details-divider",
onFocus: (l, p, d) => scrollIntoViewHandler({ block: 'nearest', behavior: 'smooth' })(focusKey, ref.current, d),
});
const detailFilter: Record<string, FilterOption> = {
stats: { label: "Stats", selected: details === 'stats', icon: <Info /> },
screenshots: { label: "Screenshots", selected: details === 'screenshots', icon: <Image /> },
};
if (game.achievements)
{
detailFilter.achievements = { label: "Achievements", selected: details === 'achievements', icon: <Trophy /> };
}
return <div ref={ref} className="divider justify-center bg-linear-to-t from-base-200 to-base-100 h-fit py-0 m-0 scroll-mt-32">
<FocusContext value={focusKey}>
<FilterUI showShortcuts={data.showShortcuts} rootFocusKey={data.rootFocusKey} className="bg-base-200 drop-shadow-none z-20 gap-1" id="details-filter" options={detailFilter} setSelected={setDetails} />
</FocusContext>
</div>;
}
export default function GameDetailsUI ()
{
const [recommendedGamesVisible, setRecommendedGamesVisible] = useState(false);
const { data } = Route.useLoaderData();
const { focus } = Route.useSearch();
const [, setUpdate] = useState(0);
const { ref, focusKey, focusSelf } = useFocusable({ focusKey: "game-details", preferredChildFocusKey: "main-details" });
const headerRef = useRef(null);
const sentinelRef = useRef(null);
const backgroundImage = data.path_cover ? new URL(`${RPC_URL(__HOST__)}${data?.path_cover}`) : undefined;
const mainAreaRef = useRef<HTMLDivElement>(null);
const { data: recommendedGames } = useQuery({ ...gamesRecommendedBasedOnGameQuery(data.id.source, data.id.id), enabled: recommendedGamesVisible });
useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: HandleGoBack }]);
const { shortcuts } = useShortcutContext();
useEffect(() =>
{
focusSelf();
if (focus)
{
setFocus(focus, { instant: true });
} else
{
focusSelf();
}
}, []);
useStickyDataAttr(headerRef, sentinelRef, ref);
const recommendedEmulators = data.emulators?.filter(e => e.store_exists);
const { ref: intersct } = useIntersectionObserver({
onChange: (isIntersecting, entry) =>
{
setRecommendedGamesVisible(isIntersecting);
}
});
return (
<AnimatedBackground ref={ref} backgroundKey="game-details" backgroundUrl={backgroundImage} scrolling>
<div className="z-10">
<FocusContext value={focusKey}>
<div ref={sentinelRef} className="h-0" />
<div ref={headerRef} className="sticky group top-0 bg-base-100/40 group p-2 z-15 transition-colors data-stuck:backdrop-blur-3xl">
<HeaderUI />
</div>
<div className="flex flex-col h-[80vh] overflow-hidden bg-linear-to-t from-base-100 to-base-100/40" ref={mainAreaRef}>
<Details mainAreaRef={mainAreaRef} game={data} />
</div>
<div className="bg-base-200">
<div className="divider m-0 pb-12"><div className="flex items-center gap-3 opacity-60"><Image className="sm:size-4 md:size-6" />Screenshots</div></div>
{!!data && <Screenshots screenshots={data.paths_screenshots} onFocus={(_, node) => node.scrollIntoView({ behavior: 'smooth', block: 'center' })} />}
<footer className="fixed left-0 right-0 bottom-0 w-full p-4 flex items-center justify-end z-10">
<Shortcuts shortcuts={shortcuts} />
</footer>
</div>
</FocusContext>
</div>
<GameDetailsContext value={{
update: () => setUpdate(v => v + 1)
}} >
<div className="z-10">
<FocusContext value={focusKey}>
<div ref={sentinelRef} className="h-0" />
<div ref={headerRef} className="sticky group top-0 bg-base-100/40 group p-2 z-15 transition-colors data-stuck:backdrop-blur-3xl">
<HeaderUI />
</div>
<div className="flex flex-col h-[calc(100vh-12rem)] overflow-hidden bg-linear-to-t from-base-100 to-base-100/40" ref={mainAreaRef}>
<Details mainAreaRef={mainAreaRef} />
</div>
<MoreDetails />
<div className="relative bg-base-300">
{!!recommendedEmulators && recommendedEmulators.length > 0 && <EmulatorsSection
id={`${data.id.id}-recommended`}
header={<><div className="w-2 h-5 rounded-full bg-info shadow-sm shadow-error/40" />
<h2 className="font-bold uppercase tracking-widest">
Related Emulators
</h2></>}
onFocus={scrollIntoViewHandler({ block: 'center' })}
onSelect={(id, focus) =>
{
Router.navigate({ to: '/store/details/emulator/$id', params: { id } });
}}
emulators={recommendedEmulators} />}
</div>
<div className="bg-base-100">
<div className="px-6 py-3">
<div className="flex items-center gap-3 mb-4">
<div className="w-2 h-5 rounded-full bg-accent shadow-sm shadow-error/40" />
<Gamepad2 className="text-accent" />
<h2 className="font-bold uppercase tracking-widest text-accent grow">
Related Games
</h2>
</div>
<GamesSection ref={intersct} showSources onSelect={(id, focus) =>
{
Router.navigate({ to: '/game/$source/$id', params: { id: id.id, source: id.source } });
}} onFocus={scrollIntoViewHandler({ block: 'center', inline: 'nearest' })} games={recommendedGames} />
</div>
</div>
</FocusContext>
</div>
<footer className="fixed right-0 bottom-0 p-4 flex items-center justify-end z-10">
<Shortcuts shortcuts={shortcuts} />
</footer>
</GameDetailsContext>
</AnimatedBackground>
);
}

View file

@ -29,7 +29,6 @@ import { HeaderAccounts, HeaderStatusBar } from "../components/Header";
import { FilterUI } from "../components/Filters";
import { AnimatedBackground } from "../components/AnimatedBackground";
import { GameList } from "../components/GameList";
import { SaveSource } from "../scripts/spatialNavigation";
import LoadingCardList from "../components/LoadingCardList";
import { AutoFocus } from "../components/AutoFocus";
import SaveScroll from "../components/SaveScroll";
@ -46,7 +45,7 @@ import { mobileCheck, useDragScroll } from "../scripts/utils";
import { AnimatedBackgroundContext } from "../scripts/contexts";
import { FrontEndId } from "@/shared/constants";
import Carousel from "../components/Carousel";
import queries from "../scripts/queries";
import { closeMutation } from "@queries/system";
export const Route = createFileRoute("/")({
component: ConsoleHomeUI,
@ -125,20 +124,17 @@ function HomeList (data: {
function handleGameSelect (id: FrontEndId, source: string | null, sourceId: string | null)
{
SaveSource('details', { search: { filter: data.selectedFilter } });
Router.navigate({ to: '/game/$source/$id', params: { id: String(sourceId ?? id.id), source: source ?? id.source }, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/game/$source/$id', params: { id: String(sourceId ?? id.id), source: source ?? id.source } });
};
const handleCollectionSelect = (id: string) =>
{
SaveSource('game-list', { search: { filter: data.selectedFilter } });
Router.navigate({ to: `/collection/${id}`, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: `/collection/${id}` });
};
const handlePlatformSelect = (source: string, id: string) =>
{
SaveSource('game-list', { search: { filter: data.selectedFilter } });
Router.navigate({ to: `/platform/${source}/${id}`, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: `/platform/${source}/${id}` });
};
let activeList: JSX.Element;
@ -224,7 +220,6 @@ function MainMenu ()
focusKey: `main-menu`,
trackChildren: true,
});
const navigate = useNavigate();
return (
<ul
ref={ref}
@ -233,13 +228,13 @@ function MainMenu ()
>
<FocusContext.Provider value={focusKey}>
<CircleIcon
action={() => navigate({ to: "/games", viewTransition: { types: ['zoom-in'] } })}
action={() => Router.navigate({ to: "/games" })}
icon={<Gamepad2 />}
label="Home"
type="secondary"
/>
<CircleIcon icon={<MessageSquare />} label="News" />
<CircleIcon type="info" icon={<Store />} action={() => navigate({ to: "/store/tab", viewTransition: { types: ['zoom-in'] } })} label="Shop" />
<CircleIcon type="info" icon={<Store />} action={() => Router.navigate({ to: "/store/tab" })} label="Shop" />
<CircleIcon icon={<Image />} label="Album" />
<CircleIcon
icon={<Gamepad2 />}
@ -248,8 +243,7 @@ function MainMenu ()
<CircleIcon
action={() =>
{
SaveSource('settings');
navigate({ to: "/settings/accounts", viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/settings/accounts' });
}}
icon={<Settings />}
label="Settings"
@ -294,7 +288,7 @@ export default function ConsoleHomeUI ()
{
const { filter } = Route.useSearch();
const close = useMutation(queries.system.closeMutation);
const close = useMutation(closeMutation);
const { ref, focusKey } = useFocusable({
forceFocus: true,
@ -304,29 +298,7 @@ export default function ConsoleHomeUI ()
preferredChildFocusKey: `home-list`,
});
const setFilter = (filter: string) => Router.navigate({ to: '/', search: { filter } });
useShortcuts(focusKey, () => [
{
action: () =>
{
const filterKeys = Object.keys(filters);
const filterIndex = Math.max(0, filterKeys.indexOf(filter));
const selectedFilterIndex = Math.min(filterIndex + 1, filterKeys.length - 1);
Router.navigate({ to: '/', search: { filter: filterKeys[selectedFilterIndex] } });
},
button: GamePadButtonCode.R1
},
{
action: () =>
{
const filterKeys = Object.keys(filters);
const filterIndex = Math.max(0, filterKeys.indexOf(filter));
const selectedFilterIndex = Math.max(0, filterIndex - 1,);
Router.navigate({ to: '/', search: { filter: filterKeys[selectedFilterIndex] } });
},
button: GamePadButtonCode.L1
}], [filter]);
const setFilter = (filter: string) => Router.navigate({ to: '/', search: { filter }, viewTransition: false, replace: true });
const { shortcuts } = useShortcutContext();
const headerButtons = [];
@ -342,6 +314,7 @@ export default function ConsoleHomeUI ()
</div>
<div className=" sm:portrait:col-span-3 sm:px-2 sm:pt-2 md:row-start-2 md:col-start-1 sm:landscape:col-span-1 md:landscape:col-span-3 flex items-center md:ml-0 gap-2">
<FilterUI
rootFocusKey={focusKey}
id="home"
containerClassName="flex w-full sm:landscape:justify-start sm:portrait:justify-center md:justify-center!"
options={Object.fromEntries(Object.entries(filters).map(([key, value]) => [key, { ...value, selected: key === filter }]))}

View file

@ -8,7 +8,7 @@ import { useQuery } from '@tanstack/react-query';
import { GamePadButtonCode, useShortcutContext, useShortcuts } from '../scripts/shortcuts';
import { useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import Shortcuts from '../components/Shortcuts';
import queries from '../scripts/queries';
import { gameQuery } from '@queries/romm';
export const Route = createFileRoute('/launcher/$source/$id')({
component: RouteComponent,
@ -18,12 +18,12 @@ function RouteComponent ()
{
function HandleGoBack ()
{
Router.navigate({ to: '/game/$source/$id', viewTransition: { types: ['zoom-out'] }, params: { source, id } });
Router.navigate({ to: '/game/$source/$id', viewTransition: { types: ['zoom-out'] }, params: { source, id }, replace: true });
}
const { source, id } = Route.useParams();
const { ref, focusKey } = useFocusable({ focusKey: `launching-${source}-${id}` });
const { data } = useQuery(queries.romm.gameQuery(source, id));
const { data } = useQuery(gameQuery(source, id));
useShortcuts(focusKey, () => [{ label: "Back", button: GamePadButtonCode.B, action: HandleGoBack }]);
const { shortcuts } = useShortcutContext();

View file

@ -2,7 +2,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { CollectionsDetail } from "../components/CollectionsDetail";
import { useQuery } from "@tanstack/react-query";
import { RPC_URL } from "../../shared/constants";
import queries from "../scripts/queries";
import { platformQuery } from "@queries/romm";
export const Route = createFileRoute("/platform/$source/$id")({
component: RouteComponent
@ -22,7 +22,7 @@ function PlatformTitle (data: { pathCover: string | null, platformName?: string;
function RouteComponent ()
{
const { source, id } = Route.useParams();
const { data: platform } = useQuery(queries.romm.platformQuery(source, id));
const { data: platform } = useQuery(platformQuery(source, id));
return (
<div className="w-full h-full">

View file

@ -1,5 +1,6 @@
import queries from '@/mainview/scripts/queries';
import { systemInfoQuery } from '@queries/system';
import { useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import prettyBytes from 'pretty-bytes';
@ -10,7 +11,7 @@ export const Route = createFileRoute('/settings/about')({
function RouteComponent ()
{
const { data: systemInfo } = useQuery(queries.system.systemInfoQuery);
const { data: systemInfo } = useQuery(systemInfoQuery);
return <table className="table">
<tbody>
<tr>

View file

@ -23,7 +23,8 @@ import QRCode from "react-qr-code";
import { useJobStatus } from "@/mainview/scripts/utils";
import { useInterval } from "usehooks-ts";
import { TwitchIcon } from "@/mainview/scripts/brandIcons";
import queries from "@/mainview/scripts/queries";
import { twitchLoginMutation, twitchLoginVerificationQuery, twitchLogoutMutation } from "@queries/settings";
import { rommGetOptionsQuery, rommHasPasswordQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery } from "@queries/romm";
export const Route = createFileRoute("/settings/accounts")({
component: RouteComponent,
@ -52,14 +53,14 @@ function LoginQR (data: { id: string, isOpen: boolean, cancel: () => void, url:
function TwitchLogin ()
{
const loginStatus = useQuery(queries.settings.twitchLoginVerificationQuery);
const loginStatus = useQuery(twitchLoginVerificationQuery);
const loginMutation = useMutation({
...queries.settings.twitchLoginMutation,
...twitchLoginMutation,
onSuccess: () => loginStatus.refetch()
});
const logoutMutation = useMutation({ ...queries.settings.twitchLogoutMutation, onSuccess: () => loginStatus.refetch() });
const logoutMutation = useMutation({ ...twitchLogoutMutation, onSuccess: () => loginStatus.refetch() });
const { data: loginData, wsRef } = useJobStatus('twitch-login-job', { onEnded: () => loginStatus.refetch() });
@ -84,13 +85,13 @@ function TwitchLogin ()
function LoginControls (data: { hasPassword: boolean; })
{
const user = useQuery(queries.romm.rommUserQuery());
const loginMutation = useMutation(queries.romm.rommQrLoginMutation);
const user = useQuery(rommUserQuery());
const loginMutation = useMutation(rommQrLoginMutation);
const { data: statusValue, wsRef } = useJobStatus('login-job');
const context = useSettingsFormContext({});
const isMutatingRomm = useIsMutating({ mutationKey: ["romm", "auth"] }) > 0;
const logoutMutation = useMutation({
...queries.romm.rommLogoutMutation,
...rommLogoutMutation,
onSuccess: async (d, v, r, c) =>
{
user.refetch();
@ -136,9 +137,9 @@ function RouteComponent ()
preferredChildFocusKey: focus
});
const { data: hasPassword } = useQuery(queries.romm.rommHasPasswordQuery);
const { data: hostname } = useQuery(queries.romm.rommHostnameQuery);
const { data: username } = useQuery(queries.romm.rommUsernameQuery);
const { data: hasPassword } = useQuery(rommHasPasswordQuery);
const { data: hostname } = useQuery(rommHostnameQuery);
const { data: username } = useQuery(rommUsernameQuery);
const loginForm = useSettingsForm({
defaultValues: {
@ -160,7 +161,7 @@ function RouteComponent ()
}
});
const rommOnline = useQuery(queries.romm.rommGetOptionsQuery());
const rommOnline = useQuery(rommGetOptionsQuery());
useEffect(() =>
{
@ -170,7 +171,7 @@ function RouteComponent ()
}
}, [focus]);
const loginMutation = useMutation(queries.romm.rommLoginMutation);
const loginMutation = useMutation(rommLoginMutation);
let indicator = "";
if (rommOnline.isError)

View file

@ -2,7 +2,6 @@ import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-naviga
import { Block, createFileRoute } from '@tanstack/react-router';
import DownloadDirectoryOption from '@/mainview/components/options/DownloadDirectoryOption';
import { useIsMutating, useMutation, useQuery } from '@tanstack/react-query';
import queries from '@/mainview/scripts/queries';
import { DownloadsDrive } from '@/shared/constants';
import prettyBytes from 'pretty-bytes';
import classNames from 'classnames';
@ -13,6 +12,7 @@ import { OptionSpace } from '@/mainview/components/options/OptionSpace';
import { Button } from '@/mainview/components/options/Button';
import { systemApi } from '@/mainview/scripts/clientApi';
import useActiveControl from '@/mainview/scripts/gamepads';
import { changeDownloadsMutation } from '@queries/settings';
export const Route = createFileRoute('/settings/directories')({
component: RouteComponent,
@ -24,11 +24,11 @@ function DriveComponent (data: { drive: DownloadsDrive; downloadsSize: number; r
focusKey: data.drive.device,
onFocus: () => (ref.current as HTMLElement)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
});
const isMoving = useIsMutating(queries.settings.changeDownloadsMutation);
const isMoving = useIsMutating(changeDownloadsMutation);
const usedWithoutDownlods = data.drive.used - (data.drive.isCurrentlyUsed ? data.downloadsSize : 0);
const usedPercent = usedWithoutDownlods / data.drive.size;
const usedPercentRaw = data.drive.used / data.drive.size;
const changeDownloads = useMutation({ ...queries.settings.changeDownloadsMutation, onSuccess: data.refetchDrives }); data.drive.unusableReason;
const changeDownloads = useMutation({ ...changeDownloadsMutation, onSuccess: data.refetchDrives }); data.drive.unusableReason;
const shortcuts: Shortcut[] = [];
const valid = !data.drive.unusableReason && isMoving <= 0;
const handleAction = () => changeDownloads.mutate(data.drive.mountPoint);

View file

@ -14,7 +14,7 @@ import { FocusContext, setFocus, useFocusable } from '@noriginmedia/norigin-spat
import { GamePadButtonCode, useShortcuts } from '@/mainview/scripts/shortcuts';
import FilePicker from '@/mainview/components/FilePicker';
import { dirname } from 'pathe';
import queries from '@/mainview/scripts/queries';
import { autoEmulatorsQuery, customEmulatorAddMutation, customEmulatorDeleteMutation, customEmulatorRemoveValueQuery, customEmulatorsQuery, setCustomEmulatorMutation } from '@queries/settings';
export const Route = createFileRoute('/settings/emulators')({
component: RouteComponent,
@ -98,13 +98,13 @@ function EmulatorPath (data: { id: string; })
const [isSearching, setIsSearching] = useState(false);
const [dirty, setDirty] = useState(false);
const [localValue, setLocalValue] = useState<string | undefined>();
const { data: remoteValue } = useQuery(queries.settings.customEmulatorRemoveValueQuery(data.id));
const setSettingMutation = useMutation(queries.settings.setCustomEmulatorMutation(data.id, (v) =>
const { data: remoteValue } = useQuery(customEmulatorRemoveValueQuery(data.id));
const setSettingMutation = useMutation(setCustomEmulatorMutation(data.id, (v) =>
{
setLocalValue(v);
setDirty(false);
}));
const deleteMutation = useMutation(queries.settings.customEmulatorDeleteMutation(data.id));
const deleteMutation = useMutation(customEmulatorDeleteMutation(data.id));
const handleSave = useCallback(() =>
{
@ -223,11 +223,11 @@ function EmulatorBadge (data: {
function EmulatorBadges (data: { path?: string; addOverride: (emulator: string) => void; })
{
const { data: autoEmulators } = useQuery(queries.settings.autoEmulatorsQuery);
const { data: autoEmulators } = useQuery(autoEmulatorsQuery);
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'>
<FocusContext value={focusKey}>
{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} />)}
{autoEmulators?.map(e => <EmulatorBadge key={e.name} isCritical={e.isCritical} addOverride={data.addOverride} pathCover={e.logo} path={e.validSource?.binPath} exists={!!e.validSource} emulator={e.name} />)}
</FocusContext>
</div>;
}
@ -240,9 +240,9 @@ function RouteComponent ()
preferredChildFocusKey: focus
});
const { data: customEmulators } = useQuery(queries.settings.customEmulatorsQuery);
const { data: customEmulators } = useQuery(customEmulatorsQuery);
const addOverrideMutation = useMutation(queries.settings.customEmulatorAddMutation);
const addOverrideMutation = useMutation(customEmulatorAddMutation);
return <FocusContext value={focusKey}>
<ul ref={ref} className="list rounded-box gap-2">

View file

@ -8,7 +8,6 @@ import
Outlet,
createFileRoute,
useMatch,
useNavigate,
} from "@tanstack/react-router";
import { ViewTransitionOptions } from "@tanstack/router-core";
import classNames from "classnames";
@ -25,10 +24,10 @@ import { JSX, useEffect } from "react";
import { twMerge } from "tailwind-merge";
import z from "zod";
import { SettingsSchema } from "../../../shared/constants";
import { PopSource } from "../../scripts/spatialNavigation";
import { Router } from "../..";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "@/mainview/scripts/shortcuts";
import Shortcuts from "@/mainview/components/Shortcuts";
import { HandleGoBack } from "@/mainview/scripts/utils";
export const Route = createFileRoute("/settings")({
component: SettingsUI,
@ -48,21 +47,26 @@ function MenuItem (data: {
label: string;
})
{
const navigate = useNavigate();
const acitve = !!useMatch({ from: data.route as any, shouldThrow: false });;
const handleNonFocusSelect = () =>
{
const { to, search } = PopSource('settings');
navigate({ to: data.return ? to ?? data.route : data.route, viewTransition: data.viewTransition, search: data.return ? search : undefined });
if (data.return)
{
HandleGoBack();
} else if (!acitve)
{
Router.navigate({ to: data.route, viewTransition: { types: ['slide-up'] }, replace: true });
}
};
const { ref, focusSelf } = useFocusable({
focusKey: `menu-item-${data.route}`,
forceFocus: !!acitve,
onFocus: () =>
{
if (data.focusSelect)
if (data.focusSelect && !acitve)
{
navigate({ to: data.route });
Router.navigate({ to: data.route, viewTransition: { types: ['slide-up'] }, replace: true });
}
(ref.current as HTMLElement).scrollIntoView({ inline: 'center' });
},
@ -104,12 +108,13 @@ function SettingsMenu (data: {})
const { ref, focusKey } = useFocusable({
focusable: true,
focusKey: 'settings-menu',
preferredChildFocusKey: location.hash.replace("#", '')
preferredChildFocusKey: location.hash.replaceAll(/#|(\?.+)/g, '')
});
return <ul
ref={ref}
className="flex flex-col portrait:flex-row md:text-2xl landscape:flex-nowrap bg-base-200 sm:p-2 md:p-4 sm:portrait:gap-0 sm:landscape:gap-0 md:landscape:w-128 md:gap-2! rounded-4xl overflow-auto portrait:w-full"
style={{ viewTransitionName: 'settings-menu' }}
>
<FocusContext value={focusKey}>
<MenuItem
@ -147,25 +152,12 @@ function SettingsMenu (data: {})
route={"/"}
return
label="Return"
viewTransition={{ types: ['zoom-out'] }}
icon={<ArrowBigLeft />}
/>
</FocusContext>
</ul>;
}
function HandleGoBack ()
{
const { to, search } = PopSource('settings');
if (to)
{
console.log("Found source ", to, " to go back to");
}
Router.navigate({ to: to ?? "/", viewTransition: { types: ['zoom-out'] }, search });
}
export function SettingsUI ()
{
const { ref, focusKey, focusSelf } = useFocusable({

View file

@ -1,174 +1,264 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef } from "react";
import
{
useFocusable,
FocusContext,
setFocus,
} from "@noriginmedia/norigin-spatial-navigation";
import { createFileRoute } from "@tanstack/react-router";
import { GamePadButtonCode, useShortcutContext, useShortcuts } from "@/mainview/scripts/shortcuts";
import { Router } from "@/mainview";
import Shortcuts from "@/mainview/components/Shortcuts";
import { AnimatedBackground } from "@/mainview/components/AnimatedBackground";
import { PopSource } from "@/mainview/scripts/spatialNavigation";
import { systemApi } from "@/mainview/scripts/clientApi";
import queries from "@/mainview/scripts/queries";
import { Button } from "@/mainview/components/options/Button";
import { ChevronDown, Download, Info, Settings } from "lucide-react";
import { ContextDialog, ContextList, DialogEntry } from "@/mainview/components/ContextDialog";
import { FrontEndEmulator, RPC_URL } from "@/shared/constants";
import { ChevronDown, Download, Gamepad2, Info, Settings, Trash2, TriangleAlert } from "lucide-react";
import { ContextList, DialogEntry, useContextDialog } from "@/mainview/components/ContextDialog";
import { FrontEndEmulatorDetailed, RPC_URL } from "@/shared/constants";
import Screenshots from "@/mainview/components/Screenshots";
import { HeaderUI } from "@/mainview/components/Header";
import { useQuery } from "@tanstack/react-query";
import { StickyHeaderUI } from "@/mainview/components/Header";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { EmulatorsSection } from "@/mainview/components/store/EmulatorsSection";
import { scrollIntoViewHandler, useStickyDataAttr } from "@/mainview/scripts/utils";
import { HandleGoBack, scrollIntoViewHandler, useJobStatus } from "@/mainview/scripts/utils";
import toast from "react-hot-toast";
import { getErrorMessage } from "react-error-boundary";
import { emulatorStatusIcons } from "@/mainview/components/store/StoreEmulatorCard";
import StatList, { StatEntry } from "@/mainview/components/StatList";
import { GamesSection } from "@/mainview/components/store/GamesSection";
import { installEmulatorMutation, storeEmulatorDeleteMutation, storeEmulatorDetailsQuery, storeEmulatorsRecommendedQuery } from "@queries/store";
import { gamesRecommendedBasedOnEmulatorQuery } from "@queries/romm";
export const Route = createFileRoute('/store/details/emulator/$id')({
component: RouteComponent,
async loader (ctx)
{
const emulator = await ctx.context.queryClient.fetchQuery(queries.store.storeEmulatorDetailsQuery(ctx.params.id));
return { emulator };
ctx.context.queryClient.prefetchQuery(storeEmulatorDetailsQuery(ctx.params.id));
ctx.context.queryClient.prefetchQuery(storeEmulatorsRecommendedQuery);
ctx.context.queryClient.prefetchQuery(gamesRecommendedBasedOnEmulatorQuery(ctx.params.id));
}
});
function HomePageLink (data: { homepage: string; })
function HomePageLink (data: { homepage?: string; })
{
const { ref } = useFocusable({ focusKey: 'homepage-link' });
return <a ref={ref} className="text-lg text-info cursor-pointer focusable focusable-accent focusable-hover bg-base-200 rounded-full px-4 py-1" onClick={() => systemApi.api.system.open.post({ url: data.homepage })}>{data.homepage}</a>;
return <a
ref={ref}
className="text-lg text-info cursor-pointer focusable focusable-accent focusable-hover bg-base-200 rounded-full px-4 py-1"
onClick={() =>
{
if (data.homepage) systemApi.api.system.open.post({ url: data.homepage });
}}>
{data.homepage ?? <div className="skeleton h-4 w-54" />}
</a>;
}
function TitleArea (data: { emulator: FrontEndEmulator; })
function TitleArea (data: {
emulator?: FrontEndEmulatorDetailed;
onInstall: (source: string) => void;
})
{
const [installOpen, setInstallOpen] = useState(false);
const installOptions: DialogEntry[] = [];
const queryClient = useQueryClient();
const deleteMutation = useMutation({
...storeEmulatorDeleteMutation, onSuccess: (data, variables, onMutateResult, context) => context.client.refetchQueries(storeEmulatorDetailsQuery(variables)),
});
const installProgressRef = useRef<HTMLProgressElement>(null);
const { data: installJob, status: installStatus } = useJobStatus('download-emulator', {
onError (error)
{
console.log(error);
toast.error(getErrorMessage(error) ?? "Error During Download");
},
onProgress (process)
{
if (installProgressRef.current)
installProgressRef.current.value = process;
},
onEnded (data)
{
console.log("Finished Install", data.emulator);
if (data.emulator)
queryClient.refetchQueries(storeEmulatorDetailsQuery(data.emulator));
},
});
const isInstalling = !!installJob;
const options: DialogEntry[] = [];
if (data.emulator)
{
if (!isInstalling && !data.emulator?.validSource)
{
options.push(...data.emulator.downloads.map(d =>
{
const entry: DialogEntry = {
content: `Install From: ${d.name} (${d.type})`,
type: 'primary',
id: d.name,
action: (ctx) =>
{
data.onInstall(d.name);
ctx.close();
}
};
return entry;
}));
} else if (data.emulator.sources.find(s => s.type === 'store' && s.exists))
{
options.push({
content: "Delete",
type: 'error',
icon: <Trash2 />,
action (ctx)
{
if (data.emulator) deleteMutation.mutate(data.emulator.name);
ctx.close();
},
id: "delete"
});
}
}
const { ref, focusKey } = useFocusable({
focusKey: 'title-area',
preferredChildFocusKey: "install-btn",
onFocus: () => { (ref.current as HTMLElement).scrollIntoView({ behavior: "smooth", block: 'end' }); }
});
return <div ref={ref} className="flex flex-wrap gap-4 items-center">
let installButtonContent = <></>;
if (!data.emulator)
{
installButtonContent = <span className="loading loading-spinner loading-lg"></span>;
}
else if (isInstalling)
{
installButtonContent = <><span className="loading loading-spinner loading-lg"></span>{installStatus}</>;
} else if (data.emulator.validSource)
{
installButtonContent = <><Settings /> Options</>;
} else if (data.emulator.downloads.length > 0)
{
installButtonContent = <><Download />Install</>;
} else
{
installButtonContent = <><TriangleAlert />Unsupported</>;
}
const { dialog: installOptionsDialog, setOpen } = useContextDialog("install-context-menu", {
content: <ContextList options={options} />
});
const handleOptionsOpen = () =>
{
if (isInstalling || !data.emulator || data.emulator.downloads.length <= 0) return false;
setOpen(true, 'install-btn');
};
return <div ref={ref} className="flex flex-wrap gap-4 sm:portrait:justify-center md:justify-normal items-center">
<FocusContext value={focusKey}>
<img className="size-32" src={data.emulator.logo}></img>
<div className="flex flex-col grow justify-start gap-1">
<h1 className="text-4xl font-semibold">{data.emulator.name}</h1>
<p className="flex gap-2">
{data.emulator.systems.map(({ id, name, icon }) =>
{data.emulator ? <img className="size-32" src={data.emulator.logo}></img> : <div className="skeleton h-32 w-32" />}
<div className="flex flex-col grow gap-1 sm:portrait:items-center md:items-start">
<h1 className="text-4xl font-semibold">{data.emulator?.name ?? <div className="skeleton h-10 w-84" />}</h1>
<div className="flex gap-2">
{data.emulator?.systems.map(({ id, name, icon }) =>
{
return <div key={id} className="flex gap-1 items-center text-base-content/35 mt-0.5">
{!!icon && <img className="size-6 p-1 bg-base-200 rounded-full" src={`${RPC_URL(__HOST__)}${icon}`} />}
<p className="text-nowrap text-ellipsis overflow-hidden">{name}</p>
</div>;
})}
</p>
}) ?? <><div className="skeleton h-4 w-48" /><div className="skeleton h-4 w-32" /></>}
</div>
<div className="flex pt-2 gap-1">
<HomePageLink homepage={data.emulator.homepage} />
<HomePageLink homepage={data.emulator?.homepage} />
</div>
</div>
<Button style="accent" id="install-btn" className="px-8 py-3 gap-4 rounded-4xl focusable focusable-accent" onAction={() => setInstallOpen(true)} >{
data.emulator.exists ?
<><Settings /> Options</> :
<><Download />Install</>
}
<div className="divider divider-horizontal divider-neutral m-0 opacity-20"></div>
<ChevronDown />
</Button>
<ContextDialog id="install-context-menu" open={installOpen} close={() =>
{
setInstallOpen(false);
setFocus("install-btn");
}}>
<ContextList options={installOptions}>
</ContextList>
</ContextDialog>
</FocusContext>
</div>;
<div className="flex relative sm:portrait:grow md:grow-0 justify-center gap-4">
<Button style="accent" id="install-btn" className="px-8 py-3 rounded-4xl focusable focusable-accent sm:portrait:grow flex-col gap-2" onAction={handleOptionsOpen} >
<div className="flex gap-4">
{installButtonContent}
<div className="divider divider-horizontal divider-neutral m-0 opacity-20"></div>
<ChevronDown />
</div>
{isInstalling && <progress ref={installProgressRef} className="progress" value={0} max="100"></progress>}
</Button>
</div>
{installOptionsDialog}
</FocusContext >
</div >;
}
function Description (data: { emulator: FrontEndEmulator; })
function Description (data: { emulator?: FrontEndEmulatorDetailed; })
{
return <div className="flex-col sm:px-8 md:px-16 pt-8 sm:pb-8 md:pb-12 bg-base-100">
<p>{data.emulator.description}</p>
<p>{data.emulator?.description ?? <div className="flex flex-col gap-4 w-full">
<div className="skeleton h-4 w-[40%]"></div>
<div className="skeleton h-4 w-[80%]"></div>
<div className="skeleton h-4 w-full"></div>
</div>}</p>
</div>;
}
export function RouteComponent ()
{
const { id } = Route.useParams();
const headerRef = useRef(null);
const sentinelRef = useRef(null);
const { ref, focusKey, focusSelf } = useFocusable({
focusKey: `GAME_DETAIL_${id}`,
trackChildren: true,
preferredChildFocusKey: 'title-area'
});
const { emulator } = Route.useLoaderData();
const { data: recommended } = useQuery(queries.store.storeEmulatorsRecommendedQuery);
const { data: emulator, isPending: isEmulatorPending } = useQuery(storeEmulatorDetailsQuery(id));
const { data: recommendedEmulators } = useQuery(storeEmulatorsRecommendedQuery);
const { data: recommendedGames } = useQuery(gamesRecommendedBasedOnEmulatorQuery(id));
useShortcuts(focusKey, () => [{
label: "Return",
action: () =>
{
const { to, search } = PopSource('store-details');
Router.navigate({ to: to ?? '/store/tab', viewTransition: { types: ['zoom-out'] }, search: search ?? { focus: id } });
},
action: HandleGoBack,
button: GamePadButtonCode.B
}]);
const installMutation = useMutation({
...installEmulatorMutation(id), onSuccess: (data, variables, onMutateResult, context) => context.client.refetchQueries(storeEmulatorDetailsQuery(id)),
});
useEffect(() =>
{
focusSelf();
}, []);
const { shortcuts } = useShortcutContext();
useStickyDataAttr(headerRef, sentinelRef, ref);
const stats: StatEntry[] = [];
if (emulator)
{
if (emulator.keywords)
stats.push({ label: "Tags", content: emulator.keywords });
stats.push({ label: "Systems", content: emulator.systems.map(s => s.name) });
stats.push(...emulator.sources.flatMap(s => [{ label: "Source", content: s.type, icon: emulatorStatusIcons[s.type] }, { label: "Location", content: s.binPath }]));
}
return (
<AnimatedBackground ref={ref} className="bg-base-100" scrolling>
<AnimatedBackground ref={ref} className="" scrolling>
<FocusContext.Provider value={focusKey}>
<div className="flex flex-col min-h-full z-10">
<div ref={sentinelRef} className="h-0" />
<div ref={headerRef} className='sticky not-mobile:data-stuck:backdrop-blur-xl transition-all top-0 px-2 p-2 not-data-stuck:bg-base-200 mobile:bg-base-300 z-15'>
<HeaderUI />
<StickyHeaderUI ref={ref} />
<div className="flex flex-col z-10">
<div className="w-full sm:px-8 md:px-16 pb-8 pt-12">
<TitleArea emulator={emulator} onInstall={installMutation.mutate} />
<div className='mobile:hidden left-0 top-0 absolute bg-gradient'></div>
<div className='mobile:hidden left-0 top-0 absolute bg-noise'></div>
</div>
<div className=" w-full sm:px-8 md:px-16 pb-8 pt-12">
<TitleArea emulator={emulator} />
</div>
<div className="flex flex-col bg-base-200 pt-4 min-h-0 grow text-lg">
<Screenshots screenshots={emulator.screenshots} onFocus={scrollIntoViewHandler({ block: 'end' })} />
<div className="flex flex-col bg-base-100 gap-4 pt-4 h-[50vh] min-h-128 grow text-lg">
{isEmulatorPending || (!!emulator && emulator?.screenshots.length > 0) && <Screenshots className="grow bg-base-200" screenshots={emulator?.screenshots} onFocus={scrollIntoViewHandler({ block: 'end' })} />}
<Description emulator={emulator} />
</div>
<div className='mobile:hidden bg-gradient'></div>
<div className='mobile:hidden bg-noise'></div>
</div>
<div className="flex flex-col bg-base-100 py-4">
<div className="flex flex-col bg-base-100 py-4 gap-12 z-10">
<div className="divider"> <Info className="size-12" /> Stats</div>
<ul className="flex flex-col table table-lg sm:px-8 md:px-16">
{!!emulator.keywords &&
<li className="flex flex-wrap gap-2 items-center">
<div className="font-semibold">Tags:</div>
<div className="flex flex-wrap gap-2">{emulator.keywords?.map(k => <span className="rounded-full bg-base-200 px-3 py-1">{k}</span>)}</div>
</li>
}
{!!emulator.status.source &&
<li>
<div>Source</div>
<div>{emulator.status.source}</div>
</li>
}
{!!emulator.status.location &&
<li>
<div>Location</div>
<div>{emulator.status.location}</div>
</li>
}
</ul>
<div className="relative mt-16 bg-base-200">
{recommended && <EmulatorsSection
<StatList id="emulator-details-stats" stats={stats} onFocus={scrollIntoViewHandler({ block: 'center' })} />
{recommendedEmulators && <div className="relative bg-base-200">
<EmulatorsSection
id={`${id}-recommended`}
header={<><div className="w-2 h-5 rounded-full bg-info shadow-sm shadow-error/40" />
<h2 className="font-bold uppercase tracking-widest">
@ -177,11 +267,26 @@ export function RouteComponent ()
onFocus={scrollIntoViewHandler({ block: 'center' })}
onSelect={(id, focus) =>
{
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 }
});
}}
emulators={recommended} />}
</div>
emulators={recommendedEmulators} />
</div>}
{recommendedGames && recommendedGames.length > 0 && <div className="px-6 py-3">
<div className="flex items-center gap-3 mb-4">
<div className="w-2 h-5 rounded-full bg-accent shadow-sm shadow-error/40" />
<Gamepad2 className="text-accent" />
<h2 className="font-bold uppercase tracking-widest text-accent grow">
Related Games
</h2>
</div>
<GamesSection showSources={true} onFocus={scrollIntoViewHandler({ behavior: 'smooth', block: 'center' })} onSelect={(id) =>
{
Router.navigate({
to: '/game/$source/$id', params: { id: id.id, source: id.source }
});
}} games={recommendedGames} /></div>}
</div>
<div className='flex fixed bottom-4 left-4 right-4 justify-end z-10'>
<Shortcuts shortcuts={shortcuts} />

View file

@ -8,7 +8,7 @@ import { StoreEmulatorCard } from '@/mainview/components/store/StoreEmulatorCard
import { StoreContext } from '@/mainview/scripts/contexts';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { useQuery } from '@tanstack/react-query';
import queries from '@/mainview/scripts/queries';
import { storeEmulatorsQuery } from '@queries/store';
export const Route = createFileRoute('/store/tab/emulators')({
component: RouteComponent,
@ -22,7 +22,7 @@ function RouteComponent ()
preferredChildFocusKey: focus
});
const storeContext = useContext(StoreContext);
const { data: emulators } = useQuery(queries.store.storeEmulatorsQuery);
const { data: emulators } = useQuery(storeEmulatorsQuery);
useEffect(() =>
{

View file

@ -6,7 +6,7 @@ import { useInfiniteQuery } from '@tanstack/react-query';
import FrontEndGameCard from '@/mainview/components/FrontEndGameCard';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import LoadMoreButton from '@/mainview/components/LoadMoreButton';
import queries from '@/mainview/scripts/queries';
import { storeGamesInfiniteQuery } from '@queries/store';
export const Route = createFileRoute('/store/tab/games')({
component: RouteComponent
@ -17,7 +17,7 @@ function RouteComponent ()
const { focus } = useSearch({ from: '/store/tab' });
const { ref, focusKey, focusSelf } = useFocusable({ focusKey: "main-area", preferredChildFocusKey: focus });
const { data, fetchNextPage, isFetchingNextPage, isFetching } = useInfiniteQuery(queries.store.storeGamesInfiniteQuery);
const { data, fetchNextPage, isFetchingNextPage, isFetching } = useInfiniteQuery(storeGamesInfiniteQuery);
useEffect(() =>
{
@ -52,7 +52,7 @@ function RouteComponent ()
<div className="skeleton h-4 w-[40%]"></div>
</div>)}
<LoadMoreButton
lastId={data?.pages.at(-1)?.data.at(-1)?.id.id}
lastId={data?.pages.at(-1)?.data.at(-1)?.id}
onFocus={handleFocus}
isFetching={isFetchingNextPage || isFetching}
onAction={() =>

View file

@ -5,15 +5,16 @@ import { EmulatorsSection } from "../../../components/store/EmulatorsSection";
import { GamesSection } from "../../../components/store/GamesSection";
import { StatsSection } from "../../../components/store/StatsSection";
import { FrontEndGameTypeDetailed, RPC_URL } from '@/shared/constants';
import queries from '@/mainview/scripts/queries';
import { useContext, useEffect, useRef, useState } from 'react';
import { scrollIntoViewHandler } from '@/mainview/scripts/utils';
import { StoreContext } from '@/mainview/scripts/contexts';
import { useInterval } from 'usehooks-ts';
import { Button } from '@/mainview/components/options/Button';
import { HardDrive, Search } from 'lucide-react';
import { Gamepad2, HardDrive, Search, Star } from 'lucide-react';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { useQuery } from '@tanstack/react-query';
import { autoEmulatorsQuery } from '@queries/settings';
import { storeEmulatorsRecommendedQuery, storeFeaturedGamesQuery } from '@queries/store';
export const Route = createFileRoute('/store/tab/')({
component: RouteComponent
@ -106,9 +107,9 @@ function Main (data: { games?: FrontEndGameTypeDetailed[]; })
export function RouteComponent ()
{
const { focus } = useSearch({ from: '/store/tab' });
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 { data: crucialEmulators, isSuccess } = useQuery({ ...autoEmulatorsQuery, select: (data) => data.filter(e => !e.validSource && e.isCritical) });
const { data: featuredGames } = useQuery(storeFeaturedGamesQuery);
const { data: recommendedEmulators } = useQuery(storeEmulatorsRecommendedQuery);
const { focusKey, ref, focusSelf } = useFocusable({ focusKey: 'main-area', preferredChildFocusKey: focus ?? "recommended-emulators" });
const storeContext = useContext(StoreContext);
@ -137,11 +138,22 @@ export function RouteComponent ()
emulators={recommendedEmulators} />
</div>
<GamesSection
onSelect={(id, focus) => storeContext.showDetails('game', id.source, id.id, focus)}
onFocus={scrollIntoViewHandler({ block: 'center' })}
games={featuredGames}
/>
<div className="px-6 py-3">
<div className="flex items-center gap-3 mb-4">
<div className="w-2 h-5 rounded-full bg-accent shadow-sm shadow-error/40" />
<Gamepad2 className="text-accent" />
<h2 className="font-bold uppercase tracking-widest text-accent grow">
Featured Games
</h2>
<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>
<GamesSection
onSelect={(id, focus) => storeContext.showDetails('game', id.source, id.id, focus)}
onFocus={scrollIntoViewHandler({ block: 'center' })}
games={featuredGames}
/>
</div>
<StatsSection
romCount={1240}

View file

@ -4,9 +4,9 @@ import { HeaderUI } from '@/mainview/components/Header';
import Shortcuts from '@/mainview/components/Shortcuts';
import { StoreContext } from '@/mainview/scripts/contexts';
import { GamePadButtonCode, useShortcutContext, useShortcuts } from '@/mainview/scripts/shortcuts';
import { SaveSource } from '@/mainview/scripts/spatialNavigation';
import { GetFocusedElement } from '@/mainview/scripts/spatialNavigation';
import { mobileCheck, useStickyDataAttr } from '@/mainview/scripts/utils';
import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { FocusContext, getCurrentFocusKey, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { useMatchRoute } from '@tanstack/react-router';
import { createFileRoute, Outlet } from '@tanstack/react-router';
import { zodValidator } from '@tanstack/zod-adapter';
@ -33,29 +33,51 @@ function TopArea (data: { filters: Record<string, FilterOption>; })
{
const { ref, focusKey } = useFocusable({
focusKey: 'top-area',
preferredChildFocusKey: 'store-tabs',
preferredChildFocusKey: `store-tabs`,
onFocus: () =>
{
(ref.current as HTMLElement).scrollIntoView({ behavior: 'smooth', block: 'end' });
}
});
useShortcuts("STORE_ROOT", () => [{
label: "Return",
action: () => Router.navigate({ to: '/', viewTransition: { types: ['zoom-out'] } }),
button: GamePadButtonCode.B
}], []);
const handleNavigate = (s: string) =>
{
Router.navigate({ to: `/store/tab/${s === 'home' ? '' : s}`, viewTransition: { types: ['slide-up'] }, replace: true });
};
return <div ref={ref}>
<FocusContext value={focusKey}>
<div className='w-full'>
<FilterUI containerClassName='flex w-full justify-center' id="store-tabs" options={data.filters} setSelected={(s) => Router.navigate({ to: `/store/tab/${s === 'home' ? '' : s}` })} />
<FilterUI rootFocusKey='STORE_ROOT' containerClassName='flex w-full justify-center' id="store-tabs" options={data.filters}
setSelected={handleNavigate} />
</div>
</FocusContext>
</div>;
}
function StoreOutlet ()
{
const { ref, focusKey } = useFocusable({ focusKey: "STORE_OUTLET" });
return <div ref={ref}>
<FocusContext value={focusKey}>
<Outlet />
</FocusContext>
</div>;
}
function RouteComponent ()
{
// Root spatial nav container
const { ref, focusKey, focusSelf } = useFocusable({
focusKey: "STORE_ROOT",
trackChildren: true,
preferredChildFocusKey: 'top-area'
preferredChildFocusKey: 'top-area',
forceFocus: true
});
const headerRef = useRef(null);
const sentinelRef = useRef(null);
@ -65,34 +87,6 @@ function RouteComponent ()
games: { label: "Games", selected: useIsSettings('games') }
};
useShortcuts(focusKey, () => [{
label: "Return",
action: () => Router.navigate({ to: '/', viewTransition: { types: ['zoom-out'] } }),
button: GamePadButtonCode.B
},
{
action: () =>
{
const filterKeys = Object.keys(filters);
const filterIndex = Math.max(0, filterKeys.findIndex(f => filters[f].selected));
const selectedFilterIndex = Math.min(filterIndex + 1, filterKeys.length - 1);
const newFilter = filterKeys[selectedFilterIndex];
Router.navigate({ to: `/store/tab/${newFilter === 'home' ? '' : newFilter}` });
},
button: GamePadButtonCode.R1
},
{
action: () =>
{
const filterKeys = Object.keys(filters);
const filterIndex = Math.max(0, filterKeys.findIndex(f => filters[f as any].selected));
const selectedFilterIndex = Math.max(0, filterIndex - 1,);
const newFilter = filterKeys[selectedFilterIndex];
Router.navigate({ to: `/store/tab/${newFilter === 'home' ? '' : newFilter}` });
},
button: GamePadButtonCode.L1
}], [filters]);
const { shortcuts } = useShortcutContext();
const { focus } = Route.useSearch();
@ -102,31 +96,24 @@ function RouteComponent ()
{
focusSelf();
}
}, []);
const handleDetails = (type: string, source: string, id: string, focus: string) =>
{
if (type === 'emulator')
{
SaveSource('store-details', { url: location.hash.replaceAll(/#|(\?.+)/g, ''), search: { focus } });
Router.navigate({ to: '/store/details/emulator/$id', params: { id }, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/store/details/emulator/$id', params: { id } });
}
else if (type === 'game')
{
console.log(source, id);
SaveSource('details', { url: location.hash.replaceAll(/#|(\?.+)/g, ''), search: { focus } });
Router.navigate({ to: '/game/$source/$id', params: { source: source, id: id }, viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/game/$source/$id', params: { source: source, id: id } });
}
};
const match = Route.useMatch();
const goToSettings = () =>
{
SaveSource('settings', { url: match.pathname, search: { focus: "settings" } });
Router.navigate({ to: '/settings', viewTransition: { types: ['zoom-in'] } });
Router.navigate({ to: '/settings' });
};
const isMobile = mobileCheck();
@ -141,7 +128,7 @@ function RouteComponent ()
<HeaderUI buttons={[{ icon: <Settings />, id: "settings", action: goToSettings, external: true }]} />
</div>
<TopArea filters={filters} />
<Outlet />
<StoreOutlet />
<div className='flex fixed bottom-4 left-4 right-4 justify-end z-15'>
<Shortcuts shortcuts={shortcuts} />
</div>

View file

@ -1,4 +1,6 @@
export const TwitchIcon = <svg width="24" height="24" fill="currentColor" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Twitch</title>
<path d="M11.571 4.714h1.715v5.143H11.57zm4.715 0H18v5.143h-1.714zM6 0L1.714 4.286v15.428h5.143V24l4.286-4.286h3.428L22.286 12V0zm14.571 11.143l-3.428 3.428h-3.429l-3 3v-3H6.857V1.714h13.714Z" />
</svg>;
</svg>;
export const FlatpackIcon = <svg role="img" width="24" height="24" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Flathub</title><path d="M6.068 0a6 6 0 0 0-6 6 6 6 0 0 0 6 6 6 6 0 0 0 5.998-6 6 6 0 0 0-5.998-6Zm9.15.08a1.656 1.656 0 0 0-1.654 1.656v8.15a1.656 1.656 0 0 0 2.483 1.434l7.058-4.074a1.656 1.656 0 0 0 0-2.869l-1.044-.604-6.014-3.47a1.656 1.656 0 0 0-.828-.223Zm3.575 13.135a.815.815 0 0 0-.816.818v2.453h-2.454a.817.817 0 1 0 0 1.635h2.454v2.453a.817.817 0 1 0 1.635 0v-2.453h2.452a.817.817 0 1 0 0-1.635h-2.453v-2.453a.817.817 0 0 0-.818-.818zM2.865 13.5a2.794 2.794 0 0 0-2.799 2.8v4.9c0 1.55 1.248 2.8 2.8 2.8h4.9c1.55 0 2.8-1.25 2.8-2.8v-4.9c0-1.55-1.25-2.8-2.8-2.8Z" /></svg>;

View file

@ -31,4 +31,8 @@ export const FilePickerContext = createContext<{
refetchFiles: () => void;
drives: Drive[],
activeDrive: Drive | undefined;
}>({} as any);
export const GameDetailsContext = createContext<{
update: () => void;
}>({} as any);

View file

@ -1,11 +0,0 @@
import system from "./queries/system";
import settings from "./queries/settings";
import romm from "./queries/romm";
import store from "./queries/store";
export default {
system,
settings,
romm,
store
};

View file

@ -4,76 +4,116 @@ 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
})
};
export const 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;
}
});
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 rommLogoutMutation = mutationOptions({ mutationKey: ["romm", "auth", "logout"], mutationFn: () => rommApi.api.romm.logout.post() });
export const rommQrLoginMutation = mutationOptions({
mutationKey: ['login', 'qr', 'cancel'],
mutationFn: () => rommApi.api.romm.login.romm.post()
});
export const 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);
},
});
export const rommUserQuery = () => queryOptions({
...getCurrentUserApiUsersMeGetOptions(),
queryKey: ['romm', 'auth', "login"],
refetchOnWindowFocus: false,
retry: 0
});
export const rommGetOptionsQuery = () => queryOptions({
...statsApiStatsGetOptions(),
refetchInterval: 30000,
retry: false,
});
export const rommHasPasswordQuery = queryOptions({ queryKey: ['romm', 'auth', 'passLength'], queryFn: () => rommApi.api.romm.login.get().then(d => d.data?.hasPassword as boolean) });
export const rommHostnameQuery = queryOptions({ queryKey: ['romm', 'auth', 'hostname'], queryFn: () => settingsApi.api.settings({ id: 'rommAddress' }).get().then(d => d.data?.value as string) });
export const rommUsernameQuery = queryOptions({ queryKey: ['romm', 'auth', 'username'], queryFn: () => settingsApi.api.settings({ id: 'rommUser' }).get().then(d => d.data?.value as string) });
export const deleteGameMutation = (id: FrontEndId) => mutationOptions({
mutationKey: ['delete', id],
mutationFn: () => rommApi.api.romm.game({ source: id.source })({ id: id.id }).delete()
});
export const getCollectionsQuery = () => queryOptions({
...getCollectionsApiCollectionsGetOptions(),
refetchOnWindowFocus: false,
staleTime: DefaultRommStaleTime
});
export const getCollectionQuery = (id: number) => queryOptions({ ...getCollectionApiCollectionsIdGetOptions({ path: { id } }) });
export const 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
});
export const installMutation = (source: string, id: string) => mutationOptions({
mutationKey: ['install', source, id],
mutationFn: async () =>
{
const { error } = await rommApi.api.romm.game({ source })({ id }).install.post();
if (error) throw error;
}
});
export const cancelInstallMutation = (source: string, id: string) => mutationOptions({
mutationKey: ['install', 'cancel', source, id],
mutationFn: async () =>
{
const { error } = await rommApi.api.romm.game({ source })({ id }).install.delete();
if (error) throw error;
}
});
export const playMutation = mutationOptions({
mutationKey: ['play'],
mutationFn: async (data: { source: string, id: string; command_id?: string | number; }) =>
{
const { error } = await rommApi.api.romm.game({ source: data.source })({ id: data.id }).play.post({ command_id: data.command_id });
if (error)
throw error;
}
});
export const gamesRecommendedBasedOnEmulatorQuery = (id: string) => queryOptions({
queryKey: ['games', 'recommended', 'emulator', id], queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.recommended.games.emulator({ id }).get();
if (error) throw error;
return data;
}
});
export const gamesRecommendedBasedOnGameQuery = (source: string, id: string) => queryOptions({
queryKey: ['games', 'recommended', 'game', source, id],
queryFn: async () =>
{
const { data, error } = await rommApi.api.romm.recommended.games.game({ source })({ id }).get();
if (error) throw error;
return data;
}
});

View file

@ -3,132 +3,130 @@ 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) =>
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 =>
{
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"
});
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;
return response;
}
});
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 twitchLogoutMutation = mutationOptions({
mutationKey: ['twitch', 'logout'],
mutationFn: () =>
{
return rommApi.api.romm.logout.twitch.post();
}
});
export const twitchLoginMutation = mutationOptions({
mutationKey: ['twitch', 'login'],
mutationFn: (openInBrowser: boolean) =>
{
return rommApi.api.romm.login.twitch.post({ openInBrowser });
}
});
export const twitchLoginVerificationQuery = queryOptions({
queryKey: ['twitch', 'login', 'status'],
retry (failureCount, error)
{
if ((error as any).status === 404)
{
return false;
}
}),
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 failureCount < 3;
},
queryFn: async () =>
{
const { data, error, status } = await rommApi.api.romm.login.twitch.get();
if (error) throw { ...error, status };
return data;
}
});
export const customEmulatorsQuery = queryOptions({
queryKey: ['custom-emulators'], queryFn: async () =>
{
const { data, error } = await settingsApi.api.settings.emulators.custom.get();
if (error) throw error;
return data;
}
});
export const 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'] })
});
export const 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"] });
}
});
export const 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);
}
});
export const 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;
},
});
export const 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;
}
});
export const 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;
},
})
};
return value.value;
},
});

View file

@ -1,58 +1,74 @@
import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
import { infiniteQueryOptions, mutationOptions, 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;
}
})
};
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', 'featured'], 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.emulator({ id }).get();
if (error) throw error;
return data;
}
});
export const storeEmulatorDeleteMutation = mutationOptions({
mutationKey: ['store-emulator', 'delete'],
mutationFn: async (id: string) =>
{
const { error } = await storeApi.api.store.emulator({ id }).delete();
if (error) throw error;
}
});
export const 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 };
}
});
export const storeGetStatsQuery = queryOptions({
queryKey: ['store', 'stats'], queryFn: async () =>
{
const { data, error } = await storeApi.api.store.stats.get();
if (error) throw error;
return data;
}
});
export const installEmulatorMutation = (id: string) => mutationOptions({
mutationKey: ['install', 'emulator', id],
mutationFn: async (source: string) =>
{
const { data, error } = await storeApi.api.store.install.emulator({ id })({ source }).post();
if (error) throw error;
return data;
}
});

View file

@ -1,51 +1,49 @@
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({
export const drivesQuery = queryOptions({
queryKey: ['drives'],
queryFn: async () =>
{
const { data, error } = await systemApi.api.system.drives.get();
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 systemInfoQuery = queryOptions({ queryKey: ['system-info'], queryFn: () => systemApi.api.system.info.get() });
export const 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;
}
})
};
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;
},
});
export const closeMutation = mutationOptions({
mutationKey: ['close'], mutationFn: async () =>
{
const { error } = await systemApi.api.system.exit.post();
if (error) throw error;
}
});

View file

@ -9,8 +9,6 @@ import
UseFocusableResult,
} from "@noriginmedia/norigin-spatial-navigation";
import { RefObject, useEffect, useState } from "react";
import { Router } from "..";
import { RouteIds } from "@tanstack/react-router";
init({
shouldFocusDOMNode: false,
@ -22,43 +20,10 @@ let updateFocusable = SpatialNavigation.updateFocusable.bind(SpatialNavigation);
let sortSiblingsByPriority = SpatialNavigation.sortSiblingsByPriority.bind(SpatialNavigation);
let removeFocusable = SpatialNavigation.removeFocusable.bind(SpatialNavigation);
let setFocus = SpatialNavigation.setFocus.bind(SpatialNavigation);
let setCurrentFocusedKey = SpatialNavigation.setCurrentFocusedKey.bind(SpatialNavigation);
type SaveFocusType = "session" | "local";
type HistorySourceType = "settings" | 'details' | 'launch' | 'game-list' | 'store-details';
const historySourceMap = new Map<string, { to: string, search?: Record<string, any>; }>();
export function SaveSource (id: HistorySourceType, init?: { url?: string, search?: Record<string, any>; })
{
let finalUrl = init?.url ?? location.hash.replaceAll(/#|(\?.+)/g, '');
if (finalUrl)
{
historySourceMap.set(id, { to: finalUrl, search: init?.search });
}
}
export function HasSource (id: HistorySourceType)
{
return historySourceMap.has(id);
}
export function PopSource (id: HistorySourceType)
{
if (!historySourceMap.has(id))
{
return { to: undefined, search: undefined };
}
const source = historySourceMap.get(id);
historySourceMap.delete(id);
return source ?? { to: undefined, search: undefined };
}
export function PopNavigateSource (id: HistorySourceType, fallback: RouteIds<typeof Router.routeTree>)
{
const { to, search } = PopSource(id);
Router.navigate({ to: to ?? fallback, viewTransition: { types: ['zoom-out'] }, search });
}
export function GetFocusedElement (focusKey: string)
{
return (SpatialNavigation as any).focusableComponents[focusKey]?.node as HTMLElement | undefined;
@ -128,6 +93,11 @@ SpatialNavigation.setFocus = (newFocusKey, focusDetails) =>
dispatchFocusedEvent(new CustomEvent<FocusDetails>('focuschanged', { bubbles: true, detail: focusDetails }));
};
SpatialNavigation.setCurrentFocusedKey = (newFocusKey, focusDetails) =>
{
setCurrentFocusedKey(newFocusKey, focusDetails);
window.dispatchEvent(new CustomEvent<FocusDetails>('focuschanged', { bubbles: true, detail: focusDetails }));
};
SpatialNavigation.updateFocusable = (key, data) =>
{

View file

@ -1,3 +1,5 @@
import { FrontEndId } from "@/shared/constants";
export const FOCUS_KEYS = {
NAV_CATEGORIES: "NAV_CATEGORIES",
NAV_CATEGORY: (cat: string) => `NAV_CAT_${cat}`,
@ -6,6 +8,6 @@ export const FOCUS_KEYS = {
EMULATOR_SECTION: (id: string) => `EMULATOR_SECTION_${id}`,
EMULATOR_CARD: (id: string) => `EMULATOR_${id}`,
GAME_SECTION: "GAME_SECTION",
GAME_CARD: (id: string) => `GAME_${id}`,
GAME_CARD: (id: FrontEndId) => `GAME_${id.source}_${id.id}`,
STATS_SECTION: "STATS_SECTION",
} as const;

View file

@ -1,9 +1,11 @@
import { LocalSettingsSchema, LocalSettingsType } from "@/shared/constants";
import { doesFocusableExist, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { doesFocusableExist, FocusableComponentLayout, FocusDetails, getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { RefObject, useEffect, useRef, useState } from "react";
import { useLocalStorage } from "usehooks-ts";
import { jobsApi } from "./clientApi";
import { JobsAPIType } from "@/bun/api/rpc";
import { Router } from "..";
import data from "@emulators";
export function selfFocusSmart (shouldFocus: boolean, focusSelf: () => void)
{
@ -224,10 +226,14 @@ export function useDragScroll<T extends HTMLElement | null> (ref: RefObject<T>)
export function scrollIntoViewHandler (params?: ScrollIntoViewOptions)
{
return (focusKey: string, node: HTMLElement, details: any) => node.scrollIntoView({ ...params, behavior: details.instant ? 'instant' : 'smooth' });
return (focusKey: string, node: HTMLElement, details: any) =>
{
if (details.nativeEvent instanceof PointerEvent) return;
node.scrollIntoView({ ...params, behavior: details.instant ? 'instant' : 'smooth' });
};
}
export function useStickyDataAttr<T extends HTMLElement, T2 extends HTMLElement, T3 extends HTMLElement> (ref: RefObject<T | null>, sentinelRef: RefObject<T2 | null>, scrollRef: RefObject<T3 | null>)
export function useStickyDataAttr<T extends HTMLElement, T2 extends HTMLElement, T3 extends HTMLElement> (ref: RefObject<T | null>, sentinelRef: RefObject<T2 | null>, scrollRef: RefObject<T3 | null>, callback?: (stuck: boolean) => void)
{
useEffect(() =>
{
@ -239,6 +245,7 @@ export function useStickyDataAttr<T extends HTMLElement, T2 extends HTMLElement,
([entry]) =>
{
el.toggleAttribute("data-stuck", !entry.isIntersecting);
callback?.(!entry.isIntersecting);
},
{
root: scrollRef.current ?? null,
@ -249,7 +256,7 @@ export function useStickyDataAttr<T extends HTMLElement, T2 extends HTMLElement,
observer.observe(sentinel);
return () => observer.disconnect();
}, [scrollRef.current]);
}, [scrollRef.current, callback]);
}
type ExtractField<T, TYPE, K extends string> =
@ -261,18 +268,19 @@ type JobResponse<JOB extends keyof JobsAPIType['~Routes']['api']['jobs']> =
export function useJobStatus<const JOB extends keyof JobsAPIType['~Routes']['api']['jobs']> (
id: JOB,
init?: {
onProgress?: (process: number) => void,
onEnded?: () => void;
onProgress?: (process: number, data: ExtractField<JobResponse<JOB>, "data" | "started" | "progress", 'data'>) => void,
onEnded?: (data: ExtractField<JobResponse<JOB>, "completed" | "ended", 'data'>) => void;
onError?: (error: string) => void;
}
)
{
type Response = JobResponse<JOB>;
type DataPayload = ExtractField<Response, 'data' | 'progress' | 'started', 'data'>;
type DataPayload = ExtractField<Response, 'data' | 'progress' | 'started' | 'ended' | 'completed', 'data'>;
const ref = useRef<ReturnType<typeof jobsApi.api.jobs[JOB]['subscribe']>>(null);
const [data, setData] = useState<DataPayload>();
const [status, setStatus] = useState<string>();
const [error, setError] = useState<unknown>();
const [error, setError] = useState<string>();
useEffect(() =>
{
@ -287,9 +295,13 @@ export function useJobStatus<const JOB extends keyof JobsAPIType['~Routes']['api
setError(data.error);
setStatus(status);
setData(undefined);
init?.onError?.(data.error);
break;
case 'ended':
init?.onEnded?.();
setStatus(status);
setData(undefined);
init?.onEnded?.(data.data as any);
break;
case 'completed':
setStatus(status);
setData(undefined);
@ -297,7 +309,7 @@ export function useJobStatus<const JOB extends keyof JobsAPIType['~Routes']['api
default:
setData(data.data as DataPayload);
setStatus(status);
init?.onProgress?.(data.progress);
init?.onProgress?.(data.progress, data.data);
}
});
@ -311,3 +323,13 @@ export function useJobStatus<const JOB extends keyof JobsAPIType['~Routes']['api
return { data, status, error, wsRef: ref };
}
export function HandleGoBack ()
{
if (Router.history.canGoBack())
{
Router.history.back();
} else
{
Router.navigate({ to: '/', viewTransition: { types: ['zoom-out'] } });
}
}

View file

@ -32,4 +32,5 @@ interface FilterOption extends FocusParams, InteractParams
{
label: string;
selected: boolean;
icon?: any;
}