selectors.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { ActionRemote, ActionStateSetLocal, ActionStateSetRemote } from './actions';
  2. import { GlobalState } from './reducer/types';
  3. import { MusicPlayer } from './types';
  4. export function getNextPlayerStateFromAction(
  5. player: MusicPlayer | undefined,
  6. action: ActionStateSetLocal | ActionStateSetRemote | null,
  7. ): MusicPlayer | null {
  8. if (!(action && player)) {
  9. return null;
  10. }
  11. if (typeof action.payload === 'function') {
  12. return { ...player, ...action.payload(player) };
  13. }
  14. return { ...player, ...action.payload };
  15. }
  16. export const isMaster = (state: Pick<GlobalState, 'player' | 'myClientName'>): boolean =>
  17. state.player.master === state.myClientName;
  18. export const isActiveClient = (state: Pick<GlobalState, 'player' | 'myClientName'>): boolean =>
  19. isMaster(state) || state.player.activeClients.includes(state.myClientName);
  20. export const isFromOurselves = (
  21. state: Pick<GlobalState, 'myClientName'>,
  22. action: ActionRemote,
  23. ): boolean => state.myClientName === action.fromClient;
  24. export const willBeMaster = (
  25. state: Partial<GlobalState> & Pick<GlobalState, 'myClientName'>,
  26. action: ActionStateSetLocal | ActionStateSetRemote,
  27. ): boolean => {
  28. const actionHasMaster =
  29. typeof action.payload === 'function' ? !!action.payload({}).master : !!action.payload?.master;
  30. return (
  31. actionHasMaster &&
  32. state.myClientName === getNextPlayerStateFromAction(state.player, action)?.master
  33. );
  34. };
  35. export const getSongId = (state: Pick<GlobalState, 'player'>): number | null => state.player.songId;