lanpartyplayspokemon/frontend/src/TVMode.tsx
2022-10-28 15:21:51 +02:00

59 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useState } from 'react';
import './TVMode.css';
import { WGPPState } from './types';
const TVMode = () => {
const [state, setState] = useState<Partial<WGPPState>>({});
const [socket, setSocket] = useState<WebSocket>();
const [endTime, setEndTime] = useState(0);
const [secondsRemaining, setSecondsRemaining] =useState(0);
useEffect(() => {
setEndTime(Date.now() + (state?.timeUntilNextMode??15) * 1000);
const interval = setInterval(() => {
const remaining = Math.round((endTime - Date.now())/1000);
setSecondsRemaining(remaining < 0 ? 0 : remaining);
}, 500);
return () => clearInterval(interval);
}, [endTime, state?.timeUntilNextMode]);
useEffect(() => {
const url = new URL(`api/client`, window.location.href);
url.protocol = url.protocol.replace("http", "ws");
const sock = new WebSocket(url.href);
sock.onmessage = (e) => {
const newState = JSON.parse(e.data) as Partial<WGPPState>;
// Merge old and new state
setState(oldState => ({ ...oldState , ...newState }));
}
setSocket(sock);
return () => {
sock.close();
setSocket(undefined);
};
}, [])
return (state === undefined ?
<span>Loading...</span> :
<div>
<div className="heading">
<span>Mode: {state.mode}</span>
<div>
<span>{secondsRemaining}s </span>
</div>
</div>
<div>
Current state: <pre>
{JSON.stringify(state)}
</pre>
</div>
</div>
);
}
export default TVMode;