fix: Navigation blocking now working with focuesed input fields

fix: Added warning to loging with lookup provider for better UX
feat: Added ROMM Client API Token in plugin settings
This commit is contained in:
Simeon Radivoev 2026-05-05 22:24:15 +03:00
parent 7029477392
commit 4da717c26d
Signed by: simeonradivoev
GPG key ID: C16C2132A7660C8E
20 changed files with 160 additions and 96 deletions

View file

@ -4,4 +4,4 @@ Comment=GameFlow Deck
Exec=gameflow Exec=gameflow
Icon=com.simeonradivoev.gameflow-deck Icon=com.simeonradivoev.gameflow-deck
Type=Application Type=Application
Categories=Games; Categories=Game;

View file

@ -499,17 +499,17 @@ export default new Elysia()
}, { body: z.object({ source: z.string(), id: z.string() }) }) }, { body: z.object({ source: z.string(), id: z.string() }) })
.get('/lookup', async ({ query: { search } }) => .get('/lookup', async ({ query: { search } }) =>
{ {
const matches: GameLookup[] = []; const matches = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise({ search, matches }); await plugins.hooks.games.gameLookup.promise(matches, { search });
return matches; return { hadMatchers: matches.size > 0, matches: Array.from(matches.values()).flatMap(m => m) };
}, { }, {
query: z.object({ search: z.string() }) query: z.object({ search: z.string() })
}) })
.get('/lookup/:source/:id', async ({ params: { source, id } }) => .get('/lookup/:source/:id', async ({ params: { source, id } }) =>
{ {
const matches: GameLookup[] = []; const matches = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise({ source, id, matches }); await plugins.hooks.games.gameLookup.promise(matches, { source, id });
return matches; return Array.from(matches.values()).flatMap(m => m);
}) })
.post('/game/:source/:id/play', async ({ params: { id, source }, body, set }) => .post('/game/:source/:id/play', async ({ params: { id, source }, body, set }) =>
{ {

View file

@ -48,9 +48,10 @@ export async function customUpdate (source: string, id: string, destination: str
const localGame = await getLocalGame(source, id); const localGame = await getLocalGame(source, id);
if (!localGame) throw new Error("Could not find Local Game"); if (!localGame) throw new Error("Could not find Local Game");
const matches: GameLookup[] = []; const matchesMap = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise({ source: destination, id: destinationId, matches }); await plugins.hooks.games.gameLookup.promise(matchesMap, { source: destination, id: destinationId });
if (matches.length <= 0) throw new Error("Could not find destination"); const matches = matchesMap.values().next().value;
if (!matches || matches?.length <= 0) throw new Error("Could not find destination");
const match = matches[0]; const match = matches[0];
await db.transaction(async (tx) => await db.transaction(async (tx) =>

View file

@ -441,9 +441,9 @@ export async function createLocalGame (info: {
if (info.screenshotUrls.length <= 0 && info.igdb_id) if (info.screenshotUrls.length <= 0 && info.igdb_id)
{ {
const matches: GameLookup[] = []; const matches = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise({ source: 'igdb', id: String(info.igdb_id), matches }); await plugins.hooks.games.gameLookup.promise(matches, { source: 'igdb', id: String(info.igdb_id) });
info.screenshotUrls.push(...matches[0].screenshotUrls); info.screenshotUrls.push(...(matches.values().next().value?.[0].screenshotUrls ?? []));
} }
// pre-fetch screenshots // pre-fetch screenshots

View file

@ -1,6 +1,6 @@
import { EmulatorPackageType, GameListFilterType } from '@/shared/constants'; import { EmulatorPackageType, GameListFilterType } from '@/shared/constants';
import { CommandEntry, DownloadInfo, EmulatorSourceEntryType, EmulatorSupport, EmulatorSystem, FrontEndCollection, FrontEndFilterSets, FrontEndGameType, FrontEndGameTypeDetailed, FrontEndGameTypeWithIds, FrontEndId, FrontEndPlatformType, GameLookup, SaveFileChange, SaveSlots } from '@/shared/types'; import { CommandEntry, DownloadInfo, EmulatorSourceEntryType, EmulatorSupport, EmulatorSystem, FrontEndCollection, FrontEndFilterSets, FrontEndGameType, FrontEndGameTypeDetailed, FrontEndGameTypeWithIds, FrontEndId, FrontEndPlatformType, GameLookup, SaveFileChange, SaveSlots } from '@/shared/types';
import { SyncBailHook, AsyncSeriesHook, AsyncSeriesBailHook, Hook } from 'tapable'; import { SyncBailHook, AsyncSeriesHook, AsyncSeriesBailHook, Hook, AsyncSeriesWaterfallHook } from 'tapable';
export default class GameHooks export default class GameHooks
{ {
@ -96,12 +96,11 @@ export default class GameHooks
name?: string; name?: string;
family_name?: string; family_name?: string;
} | undefined>(['ctx']); } | undefined>(['ctx']);
gameLookup = new AsyncSeriesHook<[ctx: { gameLookup = new AsyncSeriesWaterfallHook<[matches: Map<string, GameLookup[]>, ctx: {
source?: string, source?: string,
id?: string; id?: string;
search?: string; search?: string;
matches: GameLookup[]; }]>(['matches', 'ctx']);
}]>(['ctx']);
fetchPlatforms = new AsyncSeriesHook<[ctx: { fetchPlatforms = new AsyncSeriesHook<[ctx: {
platforms: FrontEndPlatformType[]; platforms: FrontEndPlatformType[];
}]>(['ctx']); }]>(['ctx']);

View file

@ -32,9 +32,10 @@ export class ImportJob implements IJob<z.infer<typeof ImportJob.dataSchema>, str
async start (context: JobContext<IJob<z.infer<typeof ImportJob.dataSchema>, string>, z.infer<typeof ImportJob.dataSchema>, string>): Promise<any> async start (context: JobContext<IJob<z.infer<typeof ImportJob.dataSchema>, string>, z.infer<typeof ImportJob.dataSchema>, string>): Promise<any>
{ {
const matches: GameLookup[] = []; const matchesMap = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise({ source: this.source, id: this.id, matches }); await plugins.hooks.games.gameLookup.promise(matchesMap, { source: this.source, id: this.id });
if (matches.length <= 0) throw Error("Could not Find Game"); const matches = matchesMap.values().next().value;
if (!matches || matches.length <= 0) throw Error("Could not Find Game");
const match = matches[0]; const match = matches[0];
let cover: Buffer<ArrayBufferLike> | undefined = undefined; let cover: Buffer<ArrayBufferLike> | undefined = undefined;

View file

@ -43,13 +43,13 @@ export default class IgdbIntegration implements PluginType
{ {
await checkLoginAndRefreshTwitch(); await checkLoginAndRefreshTwitch();
ctx.hooks.games.gameLookup.tapPromise(desc.name, async ({ source, id, search, matches }) => ctx.hooks.games.gameLookup.tapPromise(desc.name, async (matches, { source, id, search }) =>
{ {
if (!process.env.TWITCH_CLIENT_ID) return; if (!process.env.TWITCH_CLIENT_ID) return matches;
const access_token = await secrets.get({ service: 'gamflow_twitch', name: 'access_token' }); const access_token = await secrets.get({ service: 'gamflow_twitch', name: 'access_token' });
if (!access_token) if (!access_token)
{ {
return; return matches;
} }
if ((source === 'igdb' && id) || search) if ((source === 'igdb' && id) || search)
@ -62,7 +62,7 @@ export default class IgdbIntegration implements PluginType
...(source === 'igdb' && id ? [igdb.where('id', '=', Number(id))] : []), ...(source === 'igdb' && id ? [igdb.where('id', '=', Number(id))] : []),
igdb.limit(10)).execute()); igdb.limit(10)).execute());
matches.push(...games.filter(g => !!g.name) matches.set(desc.name, games.filter(g => !!g.name)
.map(g => .map(g =>
{ {
const lookup: GameLookup = { const lookup: GameLookup = {
@ -89,8 +89,10 @@ export default class IgdbIntegration implements PluginType
return lookup; return lookup;
})); }));
return; return matches;
} }
return matches.set(desc.name, []);
}); });
ctx.hooks.games.platformLookup.tapPromise(desc.name, async ({ source, id, slug }) => ctx.hooks.games.platformLookup.tapPromise(desc.name, async ({ source, id, slug }) =>

View file

@ -15,9 +15,11 @@ import { validateGameSource } from "@/bun/api/games/services/statusService";
import z from "zod"; import z from "zod";
import { checkLoginAndRefreshRomm } from "@/bun/api/auth"; import { checkLoginAndRefreshRomm } from "@/bun/api/auth";
import { DownloadFileEntry, DownloadInfo, FrontEndCollection, FrontEndGameType, FrontEndGameTypeDetailed, FrontEndGameTypeDetailedAchievement, FrontEndGameTypeWithIds, FrontEndPlatformType } from "@/shared/types"; import { DownloadFileEntry, DownloadInfo, FrontEndCollection, FrontEndGameType, FrontEndGameTypeDetailed, FrontEndGameTypeDetailedAchievement, FrontEndGameTypeWithIds, FrontEndPlatformType } from "@/shared/types";
import Conf from "conf";
const SettingsSchema = z.object({ const SettingsSchema = z.object({
savesSync: z.boolean().default(false).describe("Experimental save sync support") savesSync: z.boolean().default(false).describe("Experimental save sync support"),
clientApiToken: z.string().optional().describe("Generate a long lived token from the ROMM server")
}); });
type SettingsType = z.infer<typeof SettingsSchema>; type SettingsType = z.infer<typeof SettingsSchema>;
@ -39,26 +41,34 @@ export default class RommIntegration implements PluginType<SettingsType>
return true; return true;
} }
async updateClient () async getAccessToken (config: Conf<SettingsType>)
{
if (process.env.ROMM_CLIENT_TOKEN) return process.env.ROMM_CLIENT_TOKEN;
const client_token = await config.get('clientApiToken');
if (client_token) return client_token;
return (await secrets.get({ service: 'gameflow', name: 'romm_access_token' })) ?? undefined;
}
async updateClient (pluginConfig: Conf<SettingsType>)
{ {
client.setConfig({ client.setConfig({
baseUrl: config.get('rommAddress'), baseUrl: config.get('rommAddress'),
async auth (auth) auth: (auth) =>
{ {
if (auth.scheme === 'bearer') if (auth.scheme === 'bearer')
{ {
return (await secrets.get({ service: 'gameflow', name: 'romm_access_token' })) ?? undefined; return this.getAccessToken(pluginConfig);
} }
} }
}); });
} }
async getAuthToken () async getAuthToken (config: Conf<SettingsType>)
{ {
return getAuthToken({ return getAuthToken({
scheme: 'bearer', scheme: 'bearer',
type: "http" type: "http"
}, async (a) => (await secrets.get({ service: "gameflow", name: 'romm_access_token' })) ?? undefined); }, async (a) => this.getAccessToken(config));
} }
async getAllRommPlatforms () async getAllRommPlatforms ()
@ -146,9 +156,9 @@ export default class RommIntegration implements PluginType<SettingsType>
{ {
this.isSteamDeck = isSteamDeckGameMode(); this.isSteamDeck = isSteamDeckGameMode();
ctx.setProgress(0, "Logging Into Romm"); ctx.setProgress(0, "Logging Into Romm");
await this.updateClient(); await this.updateClient(ctx.config);
await checkLoginAndRefreshRomm(); await checkLoginAndRefreshRomm();
await this.updateClient(); await this.updateClient(ctx.config);
ctx.hooks.games.fetchGames.tapPromise(desc.name, async ({ query, games }) => ctx.hooks.games.fetchGames.tapPromise(desc.name, async ({ query, games }) =>
{ {
@ -199,7 +209,7 @@ export default class RommIntegration implements PluginType<SettingsType>
{ {
if (!await this.checkRemote()) return; if (!await this.checkRemote()) return;
if (service !== 'romm') return; if (service !== 'romm') return;
await this.updateClient(); await this.updateClient(ctx.config);
}); });
ctx.hooks.games.fetchGame.tapPromise(desc.name, async ({ source, id }) => ctx.hooks.games.fetchGame.tapPromise(desc.name, async ({ source, id }) =>
@ -273,7 +283,7 @@ export default class RommIntegration implements PluginType<SettingsType>
system_slug: rommPlatform.slug, system_slug: rommPlatform.slug,
metadata: rom.metadatum, metadata: rom.metadatum,
files, files,
auth: await this.getAuthToken(), auth: await this.getAuthToken(ctx.config),
extract_path, extract_path,
id: "romm" id: "romm"
}; };
@ -310,7 +320,7 @@ export default class RommIntegration implements PluginType<SettingsType>
} }
} }
if (files.length > 0) return { files, auth: await this.getAuthToken() }; if (files.length > 0) return { files, auth: await this.getAuthToken(ctx.config) };
}); });
ctx.hooks.games.fetchRecommendedGamesForGame.tapPromise(desc.name, async ({ game, games }) => ctx.hooks.games.fetchRecommendedGamesForGame.tapPromise(desc.name, async ({ game, games }) =>
@ -445,7 +455,7 @@ export default class RommIntegration implements PluginType<SettingsType>
const rommSlot = saveFiles.data.slots.find(s => s.slot === 'gameflow' && s.latest.file_name_no_tags === slot); const rommSlot = saveFiles.data.slots.find(s => s.slot === 'gameflow' && s.latest.file_name_no_tags === slot);
if (rommSlot) if (rommSlot)
{ {
const auth = await this.getAuthToken(); const auth = await this.getAuthToken(ctx.config);
const headers: Record<string, string> = {}; const headers: Record<string, string> = {};
if (auth) if (auth)
headers['Authorization'] = auth; headers['Authorization'] = auth;
@ -535,7 +545,7 @@ export default class RommIntegration implements PluginType<SettingsType>
url.searchParams.set('emulator', command.emulator); url.searchParams.set('emulator', command.emulator);
url.searchParams.set('overwrite', "true"); url.searchParams.set('overwrite', "true");
const auth = await this.getAuthToken(); const auth = await this.getAuthToken(ctx.config);
const headers: Record<string, string> = {}; const headers: Record<string, string> = {};
if (auth) if (auth)
headers['Authorization'] = auth; headers['Authorization'] = auth;

View file

@ -1,5 +1,5 @@
import { createRef, JSX, RefObject, useEffect, useRef, useState } from "react"; import { createRef, JSX, RefObject, useEffect, useRef, useState } from "react";
import useActiveControl from "../scripts/gamepads"; import useActiveControl, { GamepadButtonEvent } from "../scripts/gamepads";
import { oneShot } from "../scripts/audio/audio"; import { oneShot } from "../scripts/audio/audio";
import { ArrowLeft, ArrowRight, CornerDownLeft, Delete, Space } from "lucide-react"; import { ArrowLeft, ArrowRight, CornerDownLeft, Delete, Space } from "lucide-react";
import { GamePadButtonCode } from "../scripts/shortcuts"; import { GamePadButtonCode } from "../scripts/shortcuts";
@ -457,11 +457,26 @@ export function GamepadKeyboard ()
if (!disposed && !hidden) requestAnimationFrame(update); if (!disposed && !hidden) requestAnimationFrame(update);
const gamepadButtonHandler = (e: Event) =>
{
if (!(e instanceof GamepadButtonEvent) || disposed || hidden) return;
if (e.button === GamePadButtonCode.L1 || e.button === GamePadButtonCode.R1 || e.button === GamePadButtonCode.L2 || e.button === GamePadButtonCode.R2)
{
e.preventDefault();
e.stopImmediatePropagation();
}
};
window.addEventListener('gamepadbuttondown', gamepadButtonHandler);
window.addEventListener('gamepadbuttonup', gamepadButtonHandler);
return () => return () =>
{ {
disposed = true; disposed = true;
Object.values(buttonRepeatTimeout).forEach(v => clearTimeout(v)); Object.values(buttonRepeatTimeout).forEach(v => clearTimeout(v));
Object.values(actionRepeatTimeout).forEach(v => clearTimeout(v)); Object.values(actionRepeatTimeout).forEach(v => clearTimeout(v));
window.removeEventListener('gamepadbuttondown', gamepadButtonHandler);
window.removeEventListener('gamepadbuttonup', gamepadButtonHandler);
}; };
}, [focusedInput, elements, shift, characters, hidden]); }, [focusedInput, elements, shift, characters, hidden]);

View file

@ -230,14 +230,6 @@ export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
const accounts: HeaderAccount[] = []; const accounts: HeaderAccount[] = [];
if (data.accounts) accounts.push(...data.accounts); if (data.accounts) accounts.push(...data.accounts);
const router = useRouter();
const { ref } = useFocusable({
focusKey: 'accounts',
onEnterPress: handleSelect,
focusable: accounts.length > 0
});
if (rommUser.data?.hasLogin || rommUser.isError) if (rommUser.data?.hasLogin || rommUser.isError)
{ {
accounts.push({ accounts.push({
@ -254,6 +246,16 @@ export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
type: 'secondary' type: 'secondary'
}); });
} }
const hasAccounts = accounts.length > 0;
const router = useRouter();
const { ref } = useFocusable({
focusKey: 'accounts',
onEnterPress: handleSelect,
focusable: hasAccounts
});
return <div onClick={handleSelect} ref={ref} style={{ viewTimelineName: "header-accounts" }} className="avatar-group cursor-pointer -space-x-6 w-fit flex items-center gap-2 drop-shadow-sm overflow-visible rounded-3xl focusable focusable-primary focusable-hover "> return <div onClick={handleSelect} ref={ref} style={{ viewTimelineName: "header-accounts" }} className="avatar-group cursor-pointer -space-x-6 w-fit flex items-center gap-2 drop-shadow-sm overflow-visible rounded-3xl focusable focusable-primary focusable-hover ">
{accounts?.map(a => <HeaderAvatar {accounts?.map(a => <HeaderAvatar
@ -316,17 +318,19 @@ export function HeaderUI (data: HeaderUIParams)
router.navigate({ to: '/settings/accounts' }); router.navigate({ to: '/settings/accounts' });
}; };
return ( return (
<FocusContext.Provider value={focusKey}>
<header <header
ref={ref} ref={ref}
className="flex items-center justify-between text-base-content" className="flex items-center justify-between text-base-content"
style={{ viewTimelineName: 'header' }} style={{ viewTimelineName: 'header' }}
> >
<FocusContext value={focusKey}>
<HeaderAccounts key={"header-accounts"} accounts={data.accounts} /> <HeaderAccounts key={"header-accounts"} accounts={data.accounts} />
{data.title} {data.title}
<HeaderStatusBar key={"header-status-bar"} buttonElements={data.buttonElements} buttons={[...data.buttons ?? [], { icon: <Settings />, id: "header-settings-btn", action: goToSettings, external: true }]} /> <HeaderStatusBar key={"header-status-bar"} buttonElements={data.buttonElements} buttons={[...data.buttons ?? [], { icon: <Settings />, id: "header-settings-btn", action: goToSettings, external: true }]} />
</header>
</FocusContext.Provider> </FocusContext>
</header >
); );
} }

View file

@ -1,13 +1,15 @@
import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation"; import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { Check, Search } from "lucide-react"; import { Check, Search, TriangleAlert } from "lucide-react";
import HeaderSearchField from "../HeaderSearchField"; import HeaderSearchField from "../HeaderSearchField";
import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts"; import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts";
import { scrollIntoViewHandler } from "@/mainview/scripts/utils"; import { scrollIntoViewHandler } from "@/mainview/scripts/utils";
import { FOCUS_KEYS } from "@/mainview/scripts/types"; import { FOCUS_KEYS } from "@/mainview/scripts/types";
import { FrontEndId, GameLookup } from "@/shared/types"; import { FrontEndId, GameLookup } from "@/shared/types";
import { gameLookupQuery } from "@/mainview/scripts/queries/romm"; import { gameLookupQuery } from "@/mainview/scripts/queries/romm";
import { Button } from "../options/Button";
import { useNavigate } from "@tanstack/react-router";
function Result (data: { function Result (data: {
match: GameLookup; match: GameLookup;
@ -65,18 +67,26 @@ export default function GameLookupElement (data: {
}) })
{ {
const { data: lookups, isFetching } = useQuery({ ...gameLookupQuery(data.search), staleTime: 1000 * 60 * 60 }); const { data: lookups, isFetching } = useQuery({ ...gameLookupQuery(data.search), staleTime: 1000 * 60 * 60 });
const navigate = useNavigate();
return <div> return <div>
<SearchField setSearch={data.setSearch} search={data.search} /> <SearchField setSearch={data.setSearch} search={data.search} />
<div className="divider">{isFetching ? <span className="loading loading-spinner loading-lg"></span> : <Search className='size-10' />}Results</div> <div className="divider">{isFetching ? <span className="loading loading-spinner loading-lg"></span> : <Search className='size-10' />}Results</div>
<ul className='flex flex-col gap-2 justify-center p-2 px-4'> <ul className='flex flex-col gap-2 justify-center p-2 px-4'>
{lookups?.map((l, i) => {!Array.isArray(lookups) && <>
{!isFetching && !lookups?.hadMatchers && <div className="flex justify-center items-center text-2xl p-16 gap-2 text-warning">
<Button onAction={e => navigate({ to: '/settings/accounts', search: { focus: 'twitch-login-space' } })} external className="gap-2" style="warning" id="setup-lookup-btn"><TriangleAlert /> Login With Lookup Provider</Button>
</div>}
{lookups?.matches.map((l, i) =>
{ {
return <Result key={i} selected={data.selected?.id === l.id && data.selected?.source === l.source} showPlatform={data.showPlatforms ?? false} match={l} onAction={(ctx) => return <Result key={i} selected={data.selected?.id === l.id && data.selected?.source === l.source} showPlatform={data.showPlatforms ?? false} match={l} onAction={(ctx) =>
{ {
data.onSelect(l); data.onSelect(l);
}} />; }} />;
})} })}
</>}
</ul> </ul>
</div>; </div>;
} }

View file

@ -27,6 +27,7 @@ export function Button (data: {
children?: any, children?: any,
className?: string, className?: string,
disabled?: boolean, disabled?: boolean,
external?: boolean,
type?: "reset" | "button" | "submit"; type?: "reset" | "button" | "submit";
style?: ButtonStyle, style?: ButtonStyle,
shortcutLabel?: string; shortcutLabel?: string;
@ -65,6 +66,7 @@ export function Button (data: {
focused ? data.focusClassName : undefined, focused ? data.focusClassName : undefined,
classNames({ classNames({
"btn-accent": focused, "btn-accent": focused,
"focusable focusable-primary focusable-hover": data.external
}, data.className))} }, data.className))}
type={data.type ?? 'button'} type={data.type ?? 'button'}
> >

View file

@ -121,7 +121,7 @@ export function OptionInput (data: {
step={data.step} step={data.step}
data-focus={"input"} data-focus={"input"}
name={data.name} name={data.name}
value={String(data.value)} value={data.value === undefined ? undefined : String(data.value)}
defaultValue={typeof data.defaultValue === 'string' ? data.defaultValue : undefined} defaultValue={typeof data.defaultValue === 'string' ? data.defaultValue : undefined}
type={data.type} type={data.type}
autoComplete={data.autocomplete} autoComplete={data.autocomplete}

View file

@ -5,6 +5,7 @@ import { StickyHeaderUI } from '@/mainview/components/Header';
import LoadingScreen from '@/mainview/components/LoadingScreen'; import LoadingScreen from '@/mainview/components/LoadingScreen';
import { Button } from '@/mainview/components/options/Button'; import { Button } from '@/mainview/components/options/Button';
import { PathSettingsOptionBase } from '@/mainview/components/options/PathSettingsOption'; import { PathSettingsOptionBase } from '@/mainview/components/options/PathSettingsOption';
import SelectMenu from '@/mainview/components/SelectMenu';
import { FloatingShortcuts } from '@/mainview/components/Shortcuts'; import { FloatingShortcuts } from '@/mainview/components/Shortcuts';
import { oneShot } from '@/mainview/scripts/audio/audio'; import { oneShot } from '@/mainview/scripts/audio/audio';
import { addManualGameMutation, allGamesInvalidateQuery, gameLookupDetails, platformLookupMatchQuery } from '@/mainview/scripts/queries/romm'; import { addManualGameMutation, allGamesInvalidateQuery, gameLookupDetails, platformLookupMatchQuery } from '@/mainview/scripts/queries/romm';
@ -252,7 +253,6 @@ function Location ()
function Details (data: {}) function Details (data: {})
{ {
const { ref, focusKey } = useFocusable({ focusKey: 'add-game-details-section' }); const { ref, focusKey } = useFocusable({ focusKey: 'add-game-details-section' });
const state = Route.useSearch(); const state = Route.useSearch();
const step = state.step ?? 0; const step = state.step ?? 0;
@ -318,11 +318,13 @@ function Steps ()
const state = Route.useSearch(); const state = Route.useSearch();
const step = state.step ?? 0; const step = state.step ?? 0;
const { ref, focusKey } = useFocusable({ focusKey: "steps", preferredChildFocusKey: `step-${step}`, saveLastFocusedChild: false }); const { ref, focusKey } = useFocusable({ focusKey: "steps", preferredChildFocusKey: `step-${step}`, saveLastFocusedChild: false });
return <ul ref={ref} className="steps pt-2" style={{ viewTransitionName: 'steps' }}> return <div ref={ref} className='flex justify-center mt-8'>
<ul className="steps pt-2" style={{ viewTransitionName: 'steps' }}>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
{StepDetails.map((s, i) => <Step key={i} index={i} label={s.label} />)} {StepDetails.map((s, i) => <Step key={i} index={i} label={s.label} />)}
</FocusContext> </FocusContext>
</ul>; </ul></div>;
} }
function RouteComponent () function RouteComponent ()
@ -374,17 +376,15 @@ function RouteComponent ()
} }
], [step]); ], [step]);
return <div ref={ref}> return <div className='absolute w-screen h-screen' ref={ref}>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<div className='absolute w-screen h-screen overflow-y-scroll'> <div className='absolute w-screen h-screen overflow-y-scroll'>
<StickyHeaderUI className='bg-base-300' ref={ref} /> <StickyHeaderUI className='bg-base-300' ref={ref} />
<div className='flex justify-center mt-8'>
<Steps /> <Steps />
</div>
<Details /> <Details />
<FloatingShortcuts /> <FloatingShortcuts />
</div> </div>
</FocusContext>
<AutoFocus focus={focusSelf} /> <AutoFocus focus={focusSelf} />
{isAddingGame && <LoadingScreen> {isAddingGame && <LoadingScreen>
<div className='flex gap-3'> <div className='flex gap-3'>
@ -392,5 +392,7 @@ function RouteComponent ()
<div>Adding Game</div> <div>Adding Game</div>
</div> </div>
</LoadingScreen>} </LoadingScreen>}
<SelectMenu rootFocusKey={focusKey} />
</FocusContext>
</div>; </div>;
} }

View file

@ -1,7 +1,7 @@
import { AnimatedBackground } from '@/mainview/components/AnimatedBackground'; import { AnimatedBackground } from '@/mainview/components/AnimatedBackground';
import { AutoFocus } from '@/mainview/components/AutoFocus'; import { AutoFocus } from '@/mainview/components/AutoFocus';
import GameLookupElement from '@/mainview/components/game/GameLookup'; import GameLookupElement from '@/mainview/components/game/GameLookup';
import { StickyHeaderUI } from '@/mainview/components/Header'; import { HeaderUI, StickyHeaderUI } from '@/mainview/components/Header';
import { FloatingShortcuts } from '@/mainview/components/Shortcuts'; import { FloatingShortcuts } from '@/mainview/components/Shortcuts';
import { customUpdateMutation, gameInvalidationQuery, gameQuery } from '@/mainview/scripts/queries/romm'; import { customUpdateMutation, gameInvalidationQuery, gameQuery } from '@/mainview/scripts/queries/romm';
import { GamePadButtonCode, useShortcuts } from '@/mainview/scripts/shortcuts'; import { GamePadButtonCode, useShortcuts } from '@/mainview/scripts/shortcuts';
@ -9,7 +9,7 @@ import { HandleGoBack } from '@/mainview/scripts/utils';
import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation'; import { FocusContext, useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { useMutation, useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { createFileRoute, useNavigate, useRouter } from '@tanstack/react-router'; import { createFileRoute, useNavigate, useRouter } from '@tanstack/react-router';
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
export const Route = createFileRoute('/game/update/$source/$id')({ export const Route = createFileRoute('/game/update/$source/$id')({
@ -44,8 +44,9 @@ function RouteComponent ()
return <AnimatedBackground ref={ref}> return <AnimatedBackground ref={ref}>
<FocusContext value={focusKey}> <FocusContext value={focusKey}>
<HeaderUI />
<div className='flex flex-col z-10 overflow-y-scroll'> <div className='flex flex-col z-10 overflow-y-scroll'>
<StickyHeaderUI ref={ref} />
<GameLookupElement <GameLookupElement
search={search} search={search}
setSearch={setSearch} setSearch={setSearch}

View file

@ -7,7 +7,7 @@ import
import { useIsMutating, useMutation, useQuery } from "@tanstack/react-query"; import { useIsMutating, useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute, useRouter } from "@tanstack/react-router"; import { createFileRoute, useRouter } from "@tanstack/react-router";
import classNames from "classnames"; import classNames from "classnames";
import { Key, Link, Lock, LogIn, LogOut, ScanQrCode, User, X } from "lucide-react"; import { Info, Key, Link, Lock, LogIn, LogOut, ScanQrCode, User, X } from "lucide-react";
import import
{ {
useEffect, useEffect,
@ -26,9 +26,13 @@ import { TwitchIcon } from "@/mainview/scripts/brandIcons";
import { twitchLoginMutation, twitchLoginVerificationQuery, twitchLogoutMutation } from "@queries/settings"; import { twitchLoginMutation, twitchLoginVerificationQuery, twitchLogoutMutation } from "@queries/settings";
import { rommGetOptionsQuery, rommLoggedInQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery, invalidateLogin } from "@queries/romm"; import { rommGetOptionsQuery, rommLoggedInQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery, invalidateLogin } from "@queries/romm";
import { systemApi } from "@/mainview/scripts/clientApi"; import { systemApi } from "@/mainview/scripts/clientApi";
import z from "zod";
export const Route = createFileRoute("/settings/accounts")({ export const Route = createFileRoute("/settings/accounts")({
component: RouteComponent, component: RouteComponent,
validateSearch: z.object({
focus: z.string().optional()
}),
}); });
function LoginQR (data: { id: string, isOpen: boolean, cancel: () => void, url: string; endsAt: Date; startedAt: Date; code?: string; }) function LoginQR (data: { id: string, isOpen: boolean, cancel: () => void, url: string; endsAt: Date; startedAt: Date; code?: string; })
@ -221,6 +225,8 @@ function RouteComponent ()
<field.FormOption label={"Romm Username"} icon={<User />} type="text" />} /> <field.FormOption label={"Romm Username"} icon={<User />} type="text" />} />
<loginForm.AppField name="password" children={(field) => <loginForm.AppField name="password" children={(field) =>
<field.FormOption label={"Romm Password"} icon={<Key />} type="password" placeholder="Password" />} /> <field.FormOption label={"Romm Password"} icon={<Key />} type="password" placeholder="Password" />} />
<loginForm.AppField name="password" children={(field) =>
<div className="flex p-4 gap-2 items-center justify-center bg-base-200 rounded-2xl"><Info /> For Romm Client API Token open plugin settings</div>} />
<loginForm.Subscribe children={(form) => <loginForm.Subscribe children={(form) =>
<OptionSpace id="login-controls-space" className="justify-end border-0"> <OptionSpace id="login-controls-space" className="justify-end border-0">
<LoginControls /> <LoginControls />

View file

@ -26,8 +26,6 @@ import
} from "lucide-react"; } from "lucide-react";
import { JSX, useMemo } from "react"; import { JSX, useMemo } from "react";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import z from "zod";
import { SettingsSchema } from "../../../shared/constants";
import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts"; import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts";
import Shortcuts from "@/mainview/components/Shortcuts"; import Shortcuts from "@/mainview/components/Shortcuts";
import { HandleGoBack } from "@/mainview/scripts/utils"; import { HandleGoBack } from "@/mainview/scripts/utils";
@ -37,9 +35,6 @@ import SelectMenu from "@/mainview/components/SelectMenu";
export const Route = createFileRoute("/settings")({ export const Route = createFileRoute("/settings")({
component: SettingsUI, component: SettingsUI,
validateSearch: z.object({
focus: z.keyof(SettingsSchema).optional()
}),
staticData: { staticData: {
enterSound: 'openSettings' enterSound: 'openSettings'
} }

View file

@ -1,7 +1,7 @@
import { getCurrentFocusKey, navigateByDirection } from "@noriginmedia/norigin-spatial-navigation"; import { getCurrentFocusKey, navigateByDirection } from "@noriginmedia/norigin-spatial-navigation";
import { GetFocusedElement } from "./spatialNavigation"; import { GetFocusedElement } from "./spatialNavigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { getLocalSetting, mobileCheck } from "./utils"; import { getLocalSetting, isTextInputFocused, mobileCheck } from "./utils";
import { oneShot } from "./audio/audio"; import { oneShot } from "./audio/audio";
import { Router } from "@/mainview"; import { Router } from "@/mainview";
@ -98,7 +98,7 @@ const throttleMap = new Map<string, number>();
const throttleAcceleration = new Map<string, number>(); const throttleAcceleration = new Map<string, number>();
function throttleNav (key: string, dir: string, event: Event) function throttleNav (key: string, dir: string, event: Event)
{ {
if (document.activeElement && document.activeElement instanceof HTMLInputElement) if (isTextInputFocused())
{ {
return false; return false;
} }

View file

@ -2,6 +2,7 @@ import { DependencyList, useEffect, useState } from "react";
import { GamepadButtonEvent } from "./gamepads"; import { GamepadButtonEvent } from "./gamepads";
import { dispatchFocusedEvent, GetFocusedTree } from "./spatialNavigation"; import { dispatchFocusedEvent, GetFocusedTree } from "./spatialNavigation";
import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation"; import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { isTextInputFocused } from "./utils";
const shortcutMap = new Map<string, (() => Shortcut[])[]>(); const shortcutMap = new Map<string, (() => Shortcut[])[]>();
const conflictSet = new Set<number>(); const conflictSet = new Set<number>();
@ -123,13 +124,22 @@ export function useShortcutContext ()
if (e.key === 'Escape') if (e.key === 'Escape')
{ {
shortcuts.get(GamePadButtonCode.B)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.B })); shortcuts.get(GamePadButtonCode.B)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.B }));
} else if (e.key === 'Backspace') } else
{
// We use backspace and space in typing
if (isTextInputFocused())
{
return false;
}
if (e.key === 'Backspace')
{ {
shortcuts.get(GamePadButtonCode.X)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.X })); shortcuts.get(GamePadButtonCode.X)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.X }));
} else if (e.key === ' ') } else if (e.key === ' ')
{ {
shortcuts.get(GamePadButtonCode.Y)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.Y })); shortcuts.get(GamePadButtonCode.Y)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.Y }));
} }
}
}; };
const handleGamepadButtonUp = (e: Event) => const handleGamepadButtonUp = (e: Event) =>

View file

@ -13,6 +13,12 @@ export type ScrollSaveParams = {
storage?: "session" | "local"; storage?: "session" | "local";
shouldSave?: boolean; shouldSave?: boolean;
}; };
export function isTextInputFocused ()
{
return document.activeElement && document.activeElement instanceof HTMLInputElement;
}
export function useScrollSave (data: ScrollSaveParams) export function useScrollSave (data: ScrollSaveParams)
{ {
useEffect(() => useEffect(() =>