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

80 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-03-07 00:56:35 +01:00
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,
2023-03-13 23:41:23 +01:00
selectRadioLoading,
2023-03-07 00:56:35 +01:00
selectRadio,
selectConnection,
} from './radioSlice';
import {
getOnWSOpen,
getOnWSClose,
getOnWSMessage,
} from './radioWS';
2023-03-07 23:08:22 +01:00
import styles from './Radio.module.scss';
2023-03-07 00:56:35 +01:00
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";
2023-03-07 00:56:35 +01:00
console.log("WS ADDR: %s", wsUrl);
return wsUrl;
};
export function RadioToggler() {
2023-03-13 23:41:23 +01:00
const loading = useAppSelector(selectRadioLoading);
2023-03-07 00:56:35 +01:00
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) {
2023-03-07 23:08:22 +01:00
if (!loading) {
onWSMessage(lastJsonMessage);
}
2023-03-07 00:56:35 +01:00
}
}, [lastJsonMessage]);
2023-03-07 00:56:35 +01:00
2023-03-07 23:08:22 +01:00
let buttonStatus = "";
let circleStyle = styles.circleDisconnected;
if (loading) {
2023-03-08 22:05:01 +01:00
buttonStatus = "Attesa";
2023-03-07 23:08:22 +01:00
circleStyle = styles.circleLoading;
2023-03-07 23:59:47 +01:00
} else if (connectionState && connectionState !== ConnectionState.DISCONNECTED) {
2023-03-07 23:08:22 +01:00
switch (radioState) {
case RadioState.STARTED:
buttonStatus = "ON AIR";
circleStyle = styles.circleStarted;
break;
case RadioState.STOPPED:
2023-03-08 22:05:01 +01:00
buttonStatus = "SPENTA";
2023-03-07 23:08:22 +01:00
circleStyle = styles.circleStopped;
break;
}
2023-03-07 00:56:35 +01:00
}
return (
<div>
2023-03-07 23:08:22 +01:00
<div className={styles.buttonWrap} aria-label="toggle-radio-state">
<div
className={styles.clicker}
2023-03-07 00:56:35 +01:00
onClick={() => dispatch(toggleRadioState())}
2023-03-07 23:08:22 +01:00
>{buttonStatus}</div>
<div className={circleStyle}></div>
2023-03-07 00:56:35 +01:00
</div>
2023-03-07 23:08:22 +01:00
</div >
2023-03-07 00:56:35 +01:00
);
}