broadcast/ui/src/features/radio/Radio.tsx

80 lines
2.4 KiB
TypeScript

import React, { useEffect } from 'react';
import useWebSocket from 'react-use-websocket';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { RadioState, ConnectionState } from '../../app/types';
import {
toggleRadioState,
selectRadioLoading,
selectRadio,
selectConnection,
} from './radioSlice';
import {
getOnWSOpen,
getOnWSClose,
getOnWSMessage,
} from './radioWS';
import styles from './Radio.module.scss';
const getWSUrl = async () => {
const proto = (window.location.protocol === "http:") ? "ws" : "wss"
const wsUrl = process.env.WS_ADDR ?
process.env.WS_ADDR :
proto + "://" + window.location.host + window.location.pathname + "liveness";
console.log("WS ADDR: %s", wsUrl);
return wsUrl;
};
export function RadioToggler() {
const loading = useAppSelector(selectRadioLoading);
const radioState = useAppSelector(selectRadio);
const connectionState = useAppSelector(selectConnection);
const dispatch = useAppDispatch();
const { lastJsonMessage } = useWebSocket(getWSUrl,
{
onOpen: getOnWSOpen(dispatch),
onClose: getOnWSClose(dispatch),
});
const onWSMessage = getOnWSMessage(dispatch);
useEffect(() => {
if (lastJsonMessage != null) {
if (!loading) {
onWSMessage(lastJsonMessage);
}
}
}, [lastJsonMessage]);
let buttonStatus = "";
let circleStyle = styles.circleDisconnected;
if (loading) {
buttonStatus = "Attesa";
circleStyle = styles.circleLoading;
} else if (connectionState && connectionState !== ConnectionState.DISCONNECTED) {
switch (radioState) {
case RadioState.STARTED:
buttonStatus = "ON AIR";
circleStyle = styles.circleStarted;
break;
case RadioState.STOPPED:
buttonStatus = "SPENTA";
circleStyle = styles.circleStopped;
break;
}
}
return (
<div>
<div className={styles.buttonWrap} aria-label="toggle-radio-state">
<div
className={styles.clicker}
onClick={() => dispatch(toggleRadioState())}
>{buttonStatus}</div>
<div className={circleStyle}></div>
</div>
</div >
);
}