games_app/prediqo_web/src/features/games/registry.ts
2026-10-27 10:49:08 +02:00

74 lines
2.1 KiB
TypeScript

import { lazy, type ComponentType, type LazyExoticComponent } from 'react';
import type { GamePlayEntry } from './types';
type LazyGamePage = LazyExoticComponent<ComponentType> & {
preload: () => Promise<unknown>;
};
const gamePreloadCache = new Map<string, Promise<unknown>>();
function lazyGame(
key: string,
loader: () => Promise<{ default: ComponentType }>
): LazyGamePage {
const preload = () => {
let pending = gamePreloadCache.get(key);
if (!pending) {
pending = loader().catch((err) => {
gamePreloadCache.delete(key);
throw err;
});
gamePreloadCache.set(key, pending);
}
return pending;
};
const Comp = lazy(loader) as LazyGamePage;
Comp.preload = preload;
return Comp;
}
/** Web UI modules keyed by backend implementation_key. */
const PAGES_BY_IMPLEMENTATION: Record<string, LazyGamePage> = {
'candle-predict': lazyGame('candle-predict', () =>
import('../candle-predict/CandlePredictPage').then((m) => ({
default: m.CandlePredictPage,
}))
),
};
/** Warm a game page chunk before the user navigates into it. */
export function preloadGameImplementation(implementationKey: string): void {
const page = PAGES_BY_IMPLEMENTATION[implementationKey];
if (!page) return;
void page.preload();
}
export function hasWebImplementation(implementationKey: string | null | undefined): boolean {
if (!implementationKey) return false;
return implementationKey in PAGES_BY_IMPLEMENTATION;
}
export function resolveGamePageByImplementation(
implementationKey: string | null | undefined
): GamePlayEntry | undefined {
if (!implementationKey || !hasWebImplementation(implementationKey)) {
return undefined;
}
return {
slug: implementationKey,
implementationKey,
Page: PAGES_BY_IMPLEMENTATION[implementationKey],
};
}
/** @deprecated Prefer resolveGamePageByImplementation after loading catalog metadata. */
export function resolveGamePage(slug: string | undefined): GamePlayEntry | undefined {
if (!slug) return undefined;
return resolveGamePageByImplementation(slug);
}
export function listWebImplementationKeys(): string[] {
return Object.keys(PAGES_BY_IMPLEMENTATION);
}