Refactor app state to be a state machine with access selectors

This commit is contained in:
Gabe Kangas
2022-05-25 20:38:40 -07:00
parent dde9878a46
commit 7b1667bf6a
21 changed files with 421 additions and 223 deletions

View File

@@ -2,20 +2,19 @@ import { Spin } from 'antd';
import { Virtuoso } from 'react-virtuoso';
import { useRef } from 'react';
import { LoadingOutlined } from '@ant-design/icons';
import { ChatMessage } from '../../../interfaces/chat-message.model';
import { ChatState } from '../../../interfaces/application-state';
import { MessageType } from '../../../interfaces/socket-events';
import s from './ChatContainer.module.scss';
import { ChatMessage } from '../../../interfaces/chat-message.model';
import { ChatUserMessage } from '..';
interface Props {
messages: ChatMessage[];
state: ChatState;
loading: boolean;
}
export default function ChatContainer(props: Props) {
const { messages, state } = props;
const loading = state === ChatState.Loading;
const { messages, loading } = props;
const chatContainerRef = useRef(null);
const spinIcon = <LoadingOutlined style={{ fontSize: '32px' }} spin />;

View File

@@ -1,6 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
interface Props {}
export default function ChatModerationNotification(props: Props) {
return <div>You are now a moderator notification component goes here</div>;
}

View File

@@ -9,27 +9,30 @@ import {
import { useRecoilState, useRecoilValue } from 'recoil';
import { useState } from 'react';
import Modal from '../../ui/Modal/Modal';
import { chatVisibilityAtom, chatDisplayNameAtom } from '../../stores/ClientConfigStore';
import { ChatState, ChatVisibilityState } from '../../../interfaces/application-state';
import {
chatVisibleToggleAtom,
chatDisplayNameAtom,
appStateAtom,
} from '../../stores/ClientConfigStore';
import s from './UserDropdown.module.scss';
import NameChangeModal from '../../modals/NameChangeModal';
import { AppStateOptions } from '../../stores/application-state';
interface Props {
username?: string;
chatState: ChatState;
}
export default function UserDropdown({ username: defaultUsername, chatState }: Props) {
const [chatVisibility, setChatVisibility] =
useRecoilState<ChatVisibilityState>(chatVisibilityAtom);
export default function UserDropdown({ username: defaultUsername }: Props) {
const username = defaultUsername || useRecoilValue(chatDisplayNameAtom);
const [showNameChangeModal, setShowNameChangeModal] = useState<boolean>(false);
const [chatToggleVisible, setChatToggleVisible] = useRecoilState(chatVisibleToggleAtom);
const appState = useRecoilValue<AppStateOptions>(appStateAtom);
const toggleChatVisibility = () => {
if (chatVisibility === ChatVisibilityState.Hidden) {
setChatVisibility(ChatVisibilityState.Visible);
if (!chatToggleVisible) {
setChatToggleVisible(true);
} else {
setChatVisibility(ChatVisibilityState.Hidden);
setChatToggleVisible(false);
}
};
@@ -45,7 +48,7 @@ export default function UserDropdown({ username: defaultUsername, chatState }: P
<Menu.Item key="1" icon={<LockOutlined />}>
Authenticate
</Menu.Item>
{chatState === ChatState.Available && (
{appState.chatAvailable && (
<Menu.Item key="3" icon={<MessageOutlined />} onClick={() => toggleChatVisibility()}>
Toggle chat
</Menu.Item>

View File

@@ -1,31 +1,32 @@
/* eslint-disable no-case-declarations */
import { useEffect } from 'react';
import { atom, useRecoilState, useSetRecoilState } from 'recoil';
import { atom, selector, useRecoilState, useSetRecoilState } from 'recoil';
import { useMachine } from '@xstate/react';
import { makeEmptyClientConfig, ClientConfig } from '../../interfaces/client-config.model';
import ClientConfigService from '../../services/client-config-service';
import ChatService from '../../services/chat-service';
import WebsocketService from '../../services/websocket-service';
import { ChatMessage } from '../../interfaces/chat-message.model';
import { ServerStatus, makeEmptyServerStatus } from '../../interfaces/server-status.model';
import {
AppState,
ChatState,
VideoState,
ChatVisibilityState,
getChatState,
getChatVisibilityState,
} from '../../interfaces/application-state';
import appStateModel, {
AppStateEvent,
AppStateOptions,
makeEmptyAppState,
} from './application-state';
import { setLocalStorage, getLocalStorage } from '../../utils/helpers';
import {
ConnectedClientInfoEvent,
MessageType,
ChatEvent,
SocketEvent,
} from '../../interfaces/socket-events';
import handleConnectedClientInfoMessage from './eventhandlers/connectedclientinfo';
import handleChatMessage from './eventhandlers/handleChatMessage';
import handleConnectedClientInfoMessage from './eventhandlers/connected-client-info-handler';
import ServerStatusService from '../../services/status-service';
const SERVER_STATUS_POLL_DURATION = 5000;
const ACCESS_TOKEN_KEY = 'accessToken';
// Server status is what gets updated such as viewer count, durations,
// stream title, online/offline state, etc.
export const serverStatusState = atom<ServerStatus>({
@@ -39,26 +40,6 @@ export const clientConfigStateAtom = atom({
default: makeEmptyClientConfig(),
});
export const appStateAtom = atom<AppState>({
key: 'appStateAtom',
default: AppState.Loading,
});
export const chatStateAtom = atom<ChatState>({
key: 'chatStateAtom',
default: ChatState.Offline,
});
export const videoStateAtom = atom<VideoState>({
key: 'videoStateAtom',
default: VideoState.Unavailable,
});
export const chatVisibilityAtom = atom<ChatVisibilityState>({
key: 'chatVisibility',
default: ChatVisibilityState.Visible,
});
export const chatDisplayNameAtom = atom<string>({
key: 'chatDisplayName',
default: null,
@@ -79,23 +60,79 @@ export const websocketServiceAtom = atom<WebsocketService>({
default: null,
});
export const appStateAtom = atom<AppStateOptions>({
key: 'appState',
default: makeEmptyAppState(),
});
export const chatVisibleToggleAtom = atom<boolean>({
key: 'chatVisibilityToggleAtom',
default: true,
});
export const isVideoPlayingAtom = atom<boolean>({
key: 'isVideoPlayingAtom',
default: false,
});
// Chat is visible if the user wishes it to be visible AND the required
// chat state is set.
export const isChatVisibleSelector = selector({
key: 'isChatVisibleSelector',
get: ({ get }) => {
const state: AppStateOptions = get(appStateAtom);
const userVisibleToggle: boolean = get(chatVisibleToggleAtom);
const accessToken: String = get(accessTokenAtom);
return accessToken && state.chatAvailable && userVisibleToggle;
},
});
// We display in an "online/live" state as long as video is actively playing.
// Even during the time where technically the server has said it's no longer
// live, however the last few seconds of video playback is still taking place.
export const isOnlineSelector = selector({
key: 'isOnlineSelector',
get: ({ get }) => {
const state: AppStateOptions = get(appStateAtom);
const isVideoPlaying: boolean = get(isVideoPlayingAtom);
return state.videoAvailable || isVideoPlaying;
},
});
// Take a nested object of state metadata and merge it into
// a single flattened node.
function mergeMeta(meta) {
return Object.keys(meta).reduce((acc, key) => {
const value = meta[key];
Object.assign(acc, value);
return acc;
}, {});
}
export function ClientConfigStore() {
const [appState, appStateSend, appStateService] = useMachine(appStateModel);
const setChatDisplayName = useSetRecoilState<string>(chatDisplayNameAtom);
const setClientConfig = useSetRecoilState<ClientConfig>(clientConfigStateAtom);
const setServerStatus = useSetRecoilState<ServerStatus>(serverStatusState);
const setChatVisibility = useSetRecoilState<ChatVisibilityState>(chatVisibilityAtom);
const setChatState = useSetRecoilState<ChatState>(chatStateAtom);
const [chatMessages, setChatMessages] = useRecoilState<ChatMessage[]>(chatMessagesAtom);
const setChatDisplayName = useSetRecoilState<string>(chatDisplayNameAtom);
const [appState, setAppState] = useRecoilState<AppState>(appStateAtom);
const [accessToken, setAccessToken] = useRecoilState<string>(accessTokenAtom);
const setWebsocketService = useSetRecoilState<WebsocketService>(websocketServiceAtom);
const setAppState = useSetRecoilState<AppStateOptions>(appStateAtom);
const setWebsocketService = useSetRecoilState<WebsocketService>(websocketServiceAtom);
let ws: WebsocketService;
const sendEvent = (event: string) => {
// console.log('---- sending event:', event);
appStateSend({ type: event });
};
const updateClientConfig = async () => {
try {
const config = await ClientConfigService.getConfig();
setClientConfig(config);
sendEvent('LOADED');
} catch (error) {
console.error(`ClientConfigService -> getConfig() ERROR: \n${error}`);
}
@@ -105,32 +142,42 @@ export function ClientConfigStore() {
try {
const status = await ServerStatusService.getStatus();
setServerStatus(status);
if (status.online) {
setAppState(AppState.Online);
} else {
setAppState(AppState.Offline);
sendEvent(AppStateEvent.Online);
} else if (!status.online) {
sendEvent(AppStateEvent.Offline);
}
return status;
} catch (error) {
sendEvent(AppStateEvent.Fail);
console.error(`serverStatusState -> getStatus() ERROR: \n${error}`);
return null;
}
return null;
};
const handleUserRegistration = async (optionalDisplayName?: string) => {
const savedAccessToken = getLocalStorage(ACCESS_TOKEN_KEY);
if (savedAccessToken) {
setAccessToken(savedAccessToken);
return;
}
try {
setAppState(AppState.Registering);
sendEvent(AppStateEvent.NeedsRegister);
const response = await ChatService.registerUser(optionalDisplayName);
console.log(`ChatService -> registerUser() response: \n${response}`);
const { accessToken: newAccessToken, displayName: newDisplayName } = response;
if (!newAccessToken) {
return;
}
console.log('setting access token', newAccessToken);
setAccessToken(newAccessToken);
// setLocalStorage('accessToken', newAccessToken);
setLocalStorage(ACCESS_TOKEN_KEY, newAccessToken);
setChatDisplayName(newDisplayName);
// sendEvent(AppStateEvent.Registered);
} catch (e) {
sendEvent(AppStateEvent.Fail);
console.error(`ChatService -> registerUser() ERROR: \n${e}`);
}
};
@@ -138,7 +185,7 @@ export function ClientConfigStore() {
const handleMessage = (message: SocketEvent) => {
switch (message.type) {
case MessageType.CONNECTED_USER_INFO:
handleConnectedClientInfoMessage(message as ConnectedClientInfoEvent);
handleConnectedClientInfoMessage(message as ConnectedClientInfoEvent, setChatDisplayName);
break;
case MessageType.CHAT:
handleChatMessage(message as ChatEvent, chatMessages, setChatMessages);
@@ -159,11 +206,12 @@ export function ClientConfigStore() {
};
const startChat = async () => {
setChatState(ChatState.Loading);
sendEvent(AppStateEvent.Loading);
try {
ws = new WebsocketService(accessToken, '/ws');
ws.handleMessage = handleMessage;
setWebsocketService(ws);
sendEvent(AppStateEvent.Loaded);
} catch (error) {
console.error(`ChatService -> startChat() ERROR: \n${error}`);
}
@@ -172,14 +220,11 @@ export function ClientConfigStore() {
useEffect(() => {
updateClientConfig();
handleUserRegistration();
}, []);
useEffect(() => {
updateServerStatus();
setInterval(() => {
updateServerStatus();
}, 5000);
updateServerStatus();
}, []);
}, SERVER_STATUS_POLL_DURATION);
}, [appState]);
useEffect(() => {
if (!accessToken) {
@@ -190,21 +235,18 @@ export function ClientConfigStore() {
startChat();
}, [accessToken]);
useEffect(() => {
const updatedChatState = getChatState(appState);
console.log('updatedChatState', updatedChatState);
setChatState(updatedChatState);
const updatedChatVisibility = getChatVisibilityState(appState);
console.log(
'app state: ',
AppState[appState],
'chat state:',
ChatState[updatedChatState],
'chat visibility:',
ChatVisibilityState[updatedChatVisibility],
);
setChatVisibility(updatedChatVisibility);
}, [appState]);
appStateService.onTransition(state => {
if (!state.changed) {
return;
}
const metadata = mergeMeta(state.meta) as AppStateOptions;
console.log('--- APP STATE: ', state.value);
console.log('--- APP META: ', metadata);
setAppState(metadata);
});
return null;
}

View File

@@ -0,0 +1,134 @@
/*
This is a finite state machine model that is used by xstate. https://xstate.js.org/
You send events to it and it changes state based on the pre-determined
modeling.
This allows for a clean and reliable way to model the current state of the
web application, and a single place to determine the flow of states.
You can paste this code into https://stately.ai/viz to see a visual state
map or install the VS Code plugin:
https://marketplace.visualstudio.com/items?itemName=statelyai.stately-vscode
*/
import { createMachine } from 'xstate';
export interface AppStateOptions {
chatAvailable: boolean;
chatLoading?: boolean;
videoAvailable: boolean;
appLoading?: boolean;
}
export function makeEmptyAppState(): AppStateOptions {
return {
chatAvailable: false,
chatLoading: true,
videoAvailable: false,
appLoading: true,
};
}
const OFFLINE_STATE: AppStateOptions = {
chatAvailable: false,
chatLoading: false,
videoAvailable: false,
appLoading: false,
};
const ONLINE_STATE: AppStateOptions = {
chatAvailable: true,
chatLoading: false,
videoAvailable: true,
appLoading: false,
};
const LOADING_STATE: AppStateOptions = {
chatAvailable: false,
chatLoading: false,
videoAvailable: false,
appLoading: true,
};
const GOODBYE_STATE: AppStateOptions = {
chatAvailable: true,
chatLoading: false,
videoAvailable: false,
appLoading: false,
};
export enum AppStateEvent {
Loading = 'LOADING',
Loaded = 'LOADED',
Online = 'ONLINE',
Offline = 'OFFLINE', // Have not pulled configuration data from the server.
NeedsRegister = 'NEEDS_REGISTER',
Fail = 'FAIL',
}
const appStateModel =
/** @xstate-layout N4IgpgJg5mDOIC5QEMAOqDKAXZWwDoAbAe2QgEsA7KAYgCUBRAcQEkMAVBxgEUVFWKxyWcsUp8QAD0QBGAGwz8ABgCscpUoDsAZgAcKgEwrtATgA0IAJ6zNS-CZMLtcuQBY9Jg5t0BfHxbRMHDwiUgpqGgA5BgZuDAB9RlYOLgkBIRExCWkEGRVFVXUtPUNjcytEAxNXfB0DbSNNORMG119-EEDsXAISMipaABkAeQBBbli0wWFRcSQpWQVlNQ0dfSNTC2tc+vwZVwMZWxNbA5kDAz8A9G6QvvDaADFRlkGpjNns2VcCleL1spbRDaA74FS6ORVfYHTSObRXTo3YIEABOYCg5FgeBRA3ozDYnB47xmWXmOQOKj22hUnl02iajjk2iBCCqdgO2n2VRcbQhCK6yPwaIxWLAOIiz1exMyc1A5KMVJpBjpDJczIqCG0enwXk0MiUENMjiUBjk-KRPSFYDIlnwYkIVDANGGj0egxY0WlnzJiF0TXwulU9LqWhMMl0LIM7ipmguIIObU85qClrRNrtADMMw7KE7hpF3Z75ukSbKFgg5Pp7PSQdTXBp9uVtlHtDG464E7okx0BanrRBbVBiMQIAAjSxOyRYy3IDPYgAU2g0y4AlDReyE0wP8EOR+OwF7SXLff7A8ZNCHYeGWedW3qlDIWkz61rLgjKCO4BIN70wgND2W8o3pyyjKrCdZ6q4sYqMmtyouimLYv+xbTDKXyakuyiuHI+QmCoJquCo2FyCyS52PURzqI+mgqIYpqwYKW62vajoAehsJyFS+paPhfoRhqUa6PgTIuLoRznComiEWaPYWpu-bMVmOYHihHxHuWRQ6pCJz0sqGgNMBBjCfohiEUoIJ0kyDF9umu5jhObE+rkqh2BCLS8XhYa6K4wGUuGtEviYZ5qNZ8k2o5x4IJJnGmlUOixoG5kGCy+G1JyXgHGJJhKByrihQQsBigAbmKjzIOQhAAK5ohF5YXJx+q2MYbieFB4KkW0yj6NBfr6vU3n5fglWFSiGblVVNWqaW6H5HY4bNFJbhKI4HV3k0rgnNlS6xm+1wpngtU5NeGoALQXDqbVBct+g5Qofh+EAA */
createMachine({
id: 'appState',
initial: 'loading',
states: {
loading: {
meta: {
...LOADING_STATE,
},
on: {
NEEDS_REGISTER: {
target: 'loading',
},
LOADED: {
target: 'ready',
},
FAIL: {
target: 'serverFailure',
},
},
},
ready: {
initial: 'offline',
states: {
online: {
meta: {
...ONLINE_STATE,
},
on: {
OFFLINE: {
target: 'goodbye',
},
},
},
offline: {
meta: {
...OFFLINE_STATE,
},
on: {
ONLINE: {
target: 'online',
},
},
},
goodbye: {
meta: {
...GOODBYE_STATE,
},
after: {
'300000': {
target: 'offline',
},
},
},
},
},
serverFailure: {
type: 'final',
},
userfailure: {
type: 'final',
},
},
});
export default appStateModel;

View File

@@ -0,0 +1,11 @@
import { ConnectedClientInfoEvent } from '../../../interfaces/socket-events';
export default function handleConnectedClientInfoMessage(
message: ConnectedClientInfoEvent,
setChatDisplayName: (string) => void,
) {
console.log('connected client', message);
const { user } = message;
const { displayName } = user;
setChatDisplayName(displayName);
}

View File

@@ -1,5 +0,0 @@
import { ConnectedClientInfoEvent } from '../../../interfaces/socket-events';
export default function handleConnectedClientInfoMessage(message: ConnectedClientInfoEvent) {
console.log('connected client', message);
}

View File

@@ -54,6 +54,13 @@
}
}
.loadingSpinner {
position: fixed;
left: 50%;
top: 50%;
z-index: 999999;
}
@media (min-width: 768px) {
.mobileChat {
display: none;

View File

@@ -1,12 +1,13 @@
import { useRecoilValue } from 'recoil';
import { Layout, Button, Tabs } from 'antd';
import { Layout, Button, Tabs, Spin } from 'antd';
import { NotificationFilled, HeartFilled } from '@ant-design/icons';
import {
chatVisibilityAtom,
clientConfigStateAtom,
chatMessagesAtom,
chatStateAtom,
isChatVisibleSelector,
serverStatusState,
appStateAtom,
isOnlineSelector,
} from '../../stores/ClientConfigStore';
import { ClientConfig } from '../../../interfaces/client-config.model';
import CustomPageContent from '../../CustomPageContent';
@@ -17,7 +18,6 @@ import Sidebar from '../Sidebar';
import Footer from '../Footer';
import ChatContainer from '../../chat/ChatContainer';
import { ChatMessage } from '../../../interfaces/chat-message.model';
import { ChatState, ChatVisibilityState } from '../../../interfaces/application-state';
import ChatTextField from '../../chat/ChatTextField/ChatTextField';
import ActionButtonRow from '../../action-buttons/ActionButtonRow';
import ActionButton from '../../action-buttons/ActionButton';
@@ -28,27 +28,27 @@ import SocialLinks from '../SocialLinks/SocialLinks';
import NotifyReminderPopup from '../NotifyReminderPopup/NotifyReminderPopup';
import ServerLogo from '../Logo/Logo';
import CategoryIcon from '../CategoryIcon/CategoryIcon';
import OfflineBanner from '../OfflineBanner/OfflineBanner';
import { AppStateOptions } from '../../stores/application-state';
const { TabPane } = Tabs;
const { Content } = Layout;
export default function ContentComponent() {
const appState = useRecoilValue<AppStateOptions>(appStateAtom);
const status = useRecoilValue<ServerStatus>(serverStatusState);
const clientConfig = useRecoilValue<ClientConfig>(clientConfigStateAtom);
const chatVisibility = useRecoilValue<ChatVisibilityState>(chatVisibilityAtom);
const isChatVisible = useRecoilValue<boolean>(isChatVisibleSelector);
const messages = useRecoilValue<ChatMessage[]>(chatMessagesAtom);
const chatState = useRecoilValue<ChatState>(chatStateAtom);
const online = useRecoilValue<boolean>(isOnlineSelector);
const { extraPageContent, version, socialHandles, name, title, tags } = clientConfig;
const { online, viewerCount, lastConnectTime, lastDisconnectTime } = status;
const { viewerCount, lastConnectTime, lastDisconnectTime } = status;
const followers: Follower[] = [];
const total = 0;
const chatVisible =
chatState === ChatState.Available && chatVisibility === ChatVisibilityState.Visible;
// This is example content. It should be removed.
const externalActions = [
{
@@ -67,8 +67,12 @@ export default function ContentComponent() {
return (
<Content className={`${s.root}`}>
<Spin className={s.loadingSpinner} size="large" spinning={appState.appLoading} />
<div className={`${s.leftCol}`}>
<OwncastPlayer source="/hls/stream.m3u8" online={online} />
{online && <OwncastPlayer source="/hls/stream.m3u8" online={online} />}
{!online && <OfflineBanner text="Stream is offline text goes here." />}
<Statusbar
online={online}
lastConnectTime={lastConnectTime}
@@ -111,16 +115,16 @@ export default function ContentComponent() {
<FollowerCollection total={total} followers={followers} />
</TabPane>
</Tabs>
{chatVisibility && (
{isChatVisible && (
<div className={`${s.mobileChat}`}>
<ChatContainer messages={messages} state={chatState} />
<ChatContainer messages={messages} loading={appState.chatLoading} />
<ChatTextField />
</div>
)}
<Footer version={version} />
</div>
</div>
{chatVisible && <Sidebar />}
{isChatVisible && <Sidebar />}
</Content>
);
}

View File

@@ -1,8 +1,5 @@
import { Layout } from 'antd';
import { useRecoilValue } from 'recoil';
import { ChatState } from '../../../interfaces/application-state';
import { OwncastLogo, UserDropdown } from '../../common';
import { chatStateAtom } from '../../stores/ClientConfigStore';
import s from './Header.module.scss';
const { Header } = Layout;
@@ -12,15 +9,13 @@ interface Props {
}
export default function HeaderComponent({ name = 'Your stream title' }: Props) {
const chatState = useRecoilValue<ChatState>(chatStateAtom);
return (
<Header className={`${s.header}`}>
<div className={`${s.logo}`}>
<OwncastLogo variant="contrast" />
<span>{name}</span>
</div>
<UserDropdown chatState={chatState} />
<UserDropdown />
</Header>
);
}

View File

@@ -3,26 +3,17 @@ import { useRecoilValue } from 'recoil';
import { ChatMessage } from '../../../interfaces/chat-message.model';
import { ChatContainer, ChatTextField } from '../../chat';
import s from './Sidebar.module.scss';
import {
chatMessagesAtom,
chatVisibilityAtom,
chatStateAtom,
} from '../../stores/ClientConfigStore';
import { ChatState, ChatVisibilityState } from '../../../interfaces/application-state';
import { chatMessagesAtom, appStateAtom } from '../../stores/ClientConfigStore';
import { AppStateOptions } from '../../stores/application-state';
export default function Sidebar() {
const messages = useRecoilValue<ChatMessage[]>(chatMessagesAtom);
const chatVisibility = useRecoilValue<ChatVisibilityState>(chatVisibilityAtom);
const chatState = useRecoilValue<ChatState>(chatStateAtom);
const appState = useRecoilValue<AppStateOptions>(appStateAtom);
return (
<Sider
className={s.root}
collapsed={chatVisibility === ChatVisibilityState.Hidden}
collapsedWidth={0}
width={320}
>
<ChatContainer messages={messages} state={chatState} />
<Sider className={s.root} collapsedWidth={0} width={320}>
<ChatContainer messages={messages} loading={appState.chatLoading} />
<ChatTextField />
</Sider>
);

View File

@@ -1,11 +1,10 @@
import React from 'react';
import { useSetRecoilState } from 'recoil';
import { useRecoilState } from 'recoil';
import VideoJS from './player';
import ViewerPing from './viewer-ping';
import VideoPoster from './VideoPoster';
import { getLocalStorage, setLocalStorage } from '../../utils/helpers';
import { videoStateAtom } from '../stores/ClientConfigStore';
import { VideoState } from '../../interfaces/application-state';
import { isVideoPlayingAtom } from '../stores/ClientConfigStore';
const PLAYER_VOLUME = 'owncast_volume';
@@ -19,8 +18,7 @@ interface Props {
export default function OwncastPlayer(props: Props) {
const playerRef = React.useRef(null);
const { source, online } = props;
const setVideoState = useSetRecoilState<VideoState>(videoStateAtom);
const [videoPlaying, setVideoPlaying] = useRecoilState<boolean>(isVideoPlayingAtom);
const setSavedVolume = () => {
try {
@@ -86,18 +84,19 @@ export default function OwncastPlayer(props: Props) {
player.on('playing', () => {
player.log('player is playing');
ping.start();
setVideoState(VideoState.Playing);
setVideoPlaying(true);
});
player.on('pause', () => {
player.log('player is paused');
ping.stop();
setVideoPlaying(false);
});
player.on('ended', () => {
player.log('player is ended');
ping.stop();
setVideoState(VideoState.Unavailable);
setVideoPlaying(false);
});
player.on('volumechange', handleVolume);
@@ -111,7 +110,7 @@ export default function OwncastPlayer(props: Props) {
</div>
)}
<div style={{ gridColumn: 1, gridRow: 1 }}>
<VideoPoster online={online} initialSrc="/logo" src="/thumbnail.jpg" />
{!videoPlaying && <VideoPoster online={online} initialSrc="/logo" src="/thumbnail.jpg" />}
</div>
</div>
);