Added language provider, fixed race condition on emulator

This commit is contained in:
2025-03-16 18:24:20 -05:00
parent 60db15e932
commit 85615121b2
8 changed files with 98 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import styles from './Emulator.module.scss';
import { GAME_SYSTEM_CORES, GameSystem, GameSystemCore } from '@/lib/game';
import { useLanguage } from '@/providers/LanguageProvider';
type SendEmulatorMessageInit = {
message:'init';
@@ -21,6 +22,7 @@ type SendEmulatorMessage = (
);
type ReceiveEmulatorMessage = (
{ message: 'iframe_loaded' } |
{ message: 'start' } |
{ message: 'ready' } |
{ message: 'save' } |
@@ -36,6 +38,7 @@ export type EmulatorProps = {
export const Emulator:React.FC<EmulatorProps> = props => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [ hasInit, setHasInit ] = useState(false);
const { t } = useLanguage();
const send = (msg:SendEmulatorMessage) => {
iframeRef.current?.contentWindow?.postMessage(msg, '*');
@@ -45,14 +48,6 @@ export const Emulator:React.FC<EmulatorProps> = props => {
if(hasInit) return;
setHasInit(true);
send({
message: 'init',
core: GAME_SYSTEM_CORES[props.system],
system: props.system,
gameId: props.gameId,
gameName: props.gameName
});
window.onmessage = e => {
if(!e.data) {
console.error('Invalid message received:', e.data);
@@ -61,6 +56,17 @@ export const Emulator:React.FC<EmulatorProps> = props => {
const msg = e.data as ReceiveEmulatorMessage;
switch(msg.message) {
case 'iframe_loaded':
if(hasInit) return;
send({
message: 'init',
core: GAME_SYSTEM_CORES[props.system],
system: props.system,
gameId: props.gameId,
gameName: props.gameName
});
break;
case 'start':
case 'ready':
case 'load':
@@ -71,7 +77,17 @@ export const Emulator:React.FC<EmulatorProps> = props => {
break
}
};
}, [ iframeRef ]);
window.onbeforeunload = (e: BeforeUnloadEvent) => {
e.preventDefault();
return t('emulator.exit_unsaved');
};
return () => {
window.onbeforeunload = null;
};
}, [ ]);
return (
<div className={styles.emulator}>