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

@ -499,17 +499,17 @@ export default new Elysia()
}, { body: z.object({ source: z.string(), id: z.string() }) })
.get('/lookup', async ({ query: { search } }) =>
{
const matches: GameLookup[] = [];
await plugins.hooks.games.gameLookup.promise({ search, matches });
return matches;
const matches = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise(matches, { search });
return { hadMatchers: matches.size > 0, matches: Array.from(matches.values()).flatMap(m => m) };
}, {
query: z.object({ search: z.string() })
})
.get('/lookup/:source/:id', async ({ params: { source, id } }) =>
{
const matches: GameLookup[] = [];
await plugins.hooks.games.gameLookup.promise({ source, id, matches });
return matches;
const matches = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise(matches, { source, id });
return Array.from(matches.values()).flatMap(m => m);
})
.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);
if (!localGame) throw new Error("Could not find Local Game");
const matches: GameLookup[] = [];
await plugins.hooks.games.gameLookup.promise({ source: destination, id: destinationId, matches });
if (matches.length <= 0) throw new Error("Could not find destination");
const matchesMap = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise(matchesMap, { source: destination, id: destinationId });
const matches = matchesMap.values().next().value;
if (!matches || matches?.length <= 0) throw new Error("Could not find destination");
const match = matches[0];
await db.transaction(async (tx) =>

View file

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

View file

@ -1,6 +1,6 @@
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 { SyncBailHook, AsyncSeriesHook, AsyncSeriesBailHook, Hook } from 'tapable';
import { SyncBailHook, AsyncSeriesHook, AsyncSeriesBailHook, Hook, AsyncSeriesWaterfallHook } from 'tapable';
export default class GameHooks
{
@ -96,12 +96,11 @@ export default class GameHooks
name?: string;
family_name?: string;
} | undefined>(['ctx']);
gameLookup = new AsyncSeriesHook<[ctx: {
gameLookup = new AsyncSeriesWaterfallHook<[matches: Map<string, GameLookup[]>, ctx: {
source?: string,
id?: string;
search?: string;
matches: GameLookup[];
}]>(['ctx']);
}]>(['matches', 'ctx']);
fetchPlatforms = new AsyncSeriesHook<[ctx: {
platforms: FrontEndPlatformType[];
}]>(['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>
{
const matches: GameLookup[] = [];
await plugins.hooks.games.gameLookup.promise({ source: this.source, id: this.id, matches });
if (matches.length <= 0) throw Error("Could not Find Game");
const matchesMap = new Map<string, GameLookup[]>();
await plugins.hooks.games.gameLookup.promise(matchesMap, { source: this.source, id: this.id });
const matches = matchesMap.values().next().value;
if (!matches || matches.length <= 0) throw Error("Could not Find Game");
const match = matches[0];
let cover: Buffer<ArrayBufferLike> | undefined = undefined;

View file

@ -43,13 +43,13 @@ export default class IgdbIntegration implements PluginType
{
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' });
if (!access_token)
{
return;
return matches;
}
if ((source === 'igdb' && id) || search)
@ -62,7 +62,7 @@ export default class IgdbIntegration implements PluginType
...(source === 'igdb' && id ? [igdb.where('id', '=', Number(id))] : []),
igdb.limit(10)).execute());
matches.push(...games.filter(g => !!g.name)
matches.set(desc.name, games.filter(g => !!g.name)
.map(g =>
{
const lookup: GameLookup = {
@ -89,8 +89,10 @@ export default class IgdbIntegration implements PluginType
return lookup;
}));
return;
return matches;
}
return matches.set(desc.name, []);
});
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 { checkLoginAndRefreshRomm } from "@/bun/api/auth";
import { DownloadFileEntry, DownloadInfo, FrontEndCollection, FrontEndGameType, FrontEndGameTypeDetailed, FrontEndGameTypeDetailedAchievement, FrontEndGameTypeWithIds, FrontEndPlatformType } from "@/shared/types";
import Conf from "conf";
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>;
@ -39,26 +41,34 @@ export default class RommIntegration implements PluginType<SettingsType>
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({
baseUrl: config.get('rommAddress'),
async auth (auth)
auth: (auth) =>
{
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({
scheme: 'bearer',
type: "http"
}, async (a) => (await secrets.get({ service: "gameflow", name: 'romm_access_token' })) ?? undefined);
}, async (a) => this.getAccessToken(config));
}
async getAllRommPlatforms ()
@ -146,9 +156,9 @@ export default class RommIntegration implements PluginType<SettingsType>
{
this.isSteamDeck = isSteamDeckGameMode();
ctx.setProgress(0, "Logging Into Romm");
await this.updateClient();
await this.updateClient(ctx.config);
await checkLoginAndRefreshRomm();
await this.updateClient();
await this.updateClient(ctx.config);
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 (service !== 'romm') return;
await this.updateClient();
await this.updateClient(ctx.config);
});
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,
metadata: rom.metadatum,
files,
auth: await this.getAuthToken(),
auth: await this.getAuthToken(ctx.config),
extract_path,
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 }) =>
@ -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);
if (rommSlot)
{
const auth = await this.getAuthToken();
const auth = await this.getAuthToken(ctx.config);
const headers: Record<string, string> = {};
if (auth)
headers['Authorization'] = auth;
@ -535,7 +545,7 @@ export default class RommIntegration implements PluginType<SettingsType>
url.searchParams.set('emulator', command.emulator);
url.searchParams.set('overwrite', "true");
const auth = await this.getAuthToken();
const auth = await this.getAuthToken(ctx.config);
const headers: Record<string, string> = {};
if (auth)
headers['Authorization'] = auth;

View file

@ -1,5 +1,5 @@
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 { ArrowLeft, ArrowRight, CornerDownLeft, Delete, Space } from "lucide-react";
import { GamePadButtonCode } from "../scripts/shortcuts";
@ -457,11 +457,26 @@ export function GamepadKeyboard ()
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 () =>
{
disposed = true;
Object.values(buttonRepeatTimeout).forEach(v => clearTimeout(v));
Object.values(actionRepeatTimeout).forEach(v => clearTimeout(v));
window.removeEventListener('gamepadbuttondown', gamepadButtonHandler);
window.removeEventListener('gamepadbuttonup', gamepadButtonHandler);
};
}, [focusedInput, elements, shift, characters, hidden]);

View file

@ -230,14 +230,6 @@ export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
const accounts: HeaderAccount[] = [];
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)
{
accounts.push({
@ -254,6 +246,16 @@ export function HeaderAccounts (data: { accounts?: HeaderAccount[]; })
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 ">
{accounts?.map(a => <HeaderAvatar
@ -316,17 +318,19 @@ export function HeaderUI (data: HeaderUIParams)
router.navigate({ to: '/settings/accounts' });
};
return (
<FocusContext.Provider value={focusKey}>
<header
ref={ref}
className="flex items-center justify-between text-base-content"
style={{ viewTimelineName: 'header' }}
>
<header
ref={ref}
className="flex items-center justify-between text-base-content"
style={{ viewTimelineName: 'header' }}
>
<FocusContext value={focusKey}>
<HeaderAccounts key={"header-accounts"} accounts={data.accounts} />
{data.title}
<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 { useQuery } from "@tanstack/react-query";
import { Check, Search } from "lucide-react";
import { Check, Search, TriangleAlert } from "lucide-react";
import HeaderSearchField from "../HeaderSearchField";
import { GamePadButtonCode, useShortcuts } from "@/mainview/scripts/shortcuts";
import { scrollIntoViewHandler } from "@/mainview/scripts/utils";
import { FOCUS_KEYS } from "@/mainview/scripts/types";
import { FrontEndId, GameLookup } from "@/shared/types";
import { gameLookupQuery } from "@/mainview/scripts/queries/romm";
import { Button } from "../options/Button";
import { useNavigate } from "@tanstack/react-router";
function Result (data: {
match: GameLookup;
@ -65,18 +67,26 @@ export default function GameLookupElement (data: {
})
{
const { data: lookups, isFetching } = useQuery({ ...gameLookupQuery(data.search), staleTime: 1000 * 60 * 60 });
const navigate = useNavigate();
return <div>
<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>
<ul className='flex flex-col gap-2 justify-center p-2 px-4'>
{lookups?.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) =>
{!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) =>
{
data.onSelect(l);
}} />;
})}
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);
}} />;
})}
</>}
</ul>
</div>;
}

View file

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

View file

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

View file

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

View file

@ -1,7 +1,7 @@
import { AnimatedBackground } from '@/mainview/components/AnimatedBackground';
import { AutoFocus } from '@/mainview/components/AutoFocus';
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 { customUpdateMutation, gameInvalidationQuery, gameQuery } from '@/mainview/scripts/queries/romm';
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 { useMutation, useQuery } from '@tanstack/react-query';
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';
export const Route = createFileRoute('/game/update/$source/$id')({
@ -44,8 +44,9 @@ function RouteComponent ()
return <AnimatedBackground ref={ref}>
<FocusContext value={focusKey}>
<HeaderUI />
<div className='flex flex-col z-10 overflow-y-scroll'>
<StickyHeaderUI ref={ref} />
<GameLookupElement
search={search}
setSearch={setSearch}

View file

@ -7,7 +7,7 @@ import
import { useIsMutating, useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute, useRouter } from "@tanstack/react-router";
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
{
useEffect,
@ -26,9 +26,13 @@ import { TwitchIcon } from "@/mainview/scripts/brandIcons";
import { twitchLoginMutation, twitchLoginVerificationQuery, twitchLogoutMutation } from "@queries/settings";
import { rommGetOptionsQuery, rommLoggedInQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery, invalidateLogin } from "@queries/romm";
import { systemApi } from "@/mainview/scripts/clientApi";
import z from "zod";
export const Route = createFileRoute("/settings/accounts")({
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; })
@ -221,6 +225,8 @@ function RouteComponent ()
<field.FormOption label={"Romm Username"} icon={<User />} type="text" />} />
<loginForm.AppField name="password" children={(field) =>
<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) =>
<OptionSpace id="login-controls-space" className="justify-end border-0">
<LoginControls />

View file

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

View file

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

View file

@ -2,6 +2,7 @@ import { DependencyList, useEffect, useState } from "react";
import { GamepadButtonEvent } from "./gamepads";
import { dispatchFocusedEvent, GetFocusedTree } from "./spatialNavigation";
import { getCurrentFocusKey } from "@noriginmedia/norigin-spatial-navigation";
import { isTextInputFocused } from "./utils";
const shortcutMap = new Map<string, (() => Shortcut[])[]>();
const conflictSet = new Set<number>();
@ -123,12 +124,21 @@ export function useShortcutContext ()
if (e.key === 'Escape')
{
shortcuts.get(GamePadButtonCode.B)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.B }));
} else if (e.key === 'Backspace')
} else
{
shortcuts.get(GamePadButtonCode.X)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.X }));
} else if (e.key === ' ')
{
shortcuts.get(GamePadButtonCode.Y)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.Y }));
// 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 }));
} else if (e.key === ' ')
{
shortcuts.get(GamePadButtonCode.Y)?.action?.(new GamepadButtonEvent('gamepadbuttondown', { button: GamePadButtonCode.Y }));
}
}
};

View file

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