Smarter/more granular event handling

This commit is contained in:
2025-02-23 16:37:39 -08:00
parent fe05a27b51
commit 687a7fc555
6 changed files with 81 additions and 99 deletions

View File

@@ -3,9 +3,9 @@ import SongTable from './SongTable';
import NowPlaying from './NowPlaying';
import AddSongPanel from './AddSongPanel';
import { TabView, Tab } from './TabView';
import { API, getDisplayTitle, PlaylistItem } from '../api/player';
import { useEventWebSocket } from '../hooks/useEventWebsocket';
import { API, getDisplayTitle, PlaylistItem, ServerEvent } from '../api/player';
import { FaMusic, FaHeart } from 'react-icons/fa';
import useWebSocket from 'react-use-websocket';
enum Tabs {
Playlist = "playlist",
@@ -96,14 +96,17 @@ const App: React.FC = () => {
}, []);
const fetchNowPlaying = useCallback(async () => {
if (volumeSettingIsLocked) {
// We are actively changing the volume, which we do actually want to send events
// continuously to the server, but we don't want to refresh our state while doing that.
return;
}
const nowPlaying = await API.getNowPlaying();
setNowPlayingSong(getDisplayTitle(nowPlaying.playingItem));
setNowPlayingFileName(nowPlaying.playingItem.filename);
setIsPlaying(!nowPlaying.isPaused);
if (!volumeSettingIsLocked) {
setVolume(nowPlaying.volume);
}
setVolume(nowPlaying.volume);
}, [volumeSettingIsLocked]);
const handleAddURL = async (url: string) => {
@@ -148,23 +151,41 @@ const App: React.FC = () => {
await API.setVolume(volume);
};
const handleWebSocketEvent = useCallback((event: any) => {
const handleWebSocketEvent = useCallback((message: MessageEvent) => {
const event = JSON.parse(message.data);
switch (event.event) {
case 'user_modify':
case 'end-file':
case 'playback-restart':
case 'metadata_update':
case ServerEvent.PlaylistUpdate:
case ServerEvent.NowPlayingUpdate:
case ServerEvent.MetadataUpdate:
case ServerEvent.MPDUpdate:
fetchPlaylist();
fetchNowPlaying();
break;
case 'favorites_update':
case ServerEvent.VolumeUpdate:
if (!volumeSettingIsLocked) {
fetchNowPlaying();
}
break;
case ServerEvent.FavoritesUpdate:
fetchFavorites();
break;
}
}, [fetchPlaylist, fetchNowPlaying, fetchFavorites]);
// Use the hook
useEventWebSocket(handleWebSocketEvent);
useWebSocket('/api/events', {
onOpen: () => {
console.log('WebSocket connected');
},
onClose: () => {
console.log('WebSocket disconnected');
},
onError: (error) => {
console.error('WebSocket error:', error);
},
onMessage: handleWebSocketEvent,
shouldReconnect: () => true,
});
// Handle visibility changes
useEffect(() => {