UserRole.tsx 1.41 KB
import React, { useCallback, useContext, useEffect, useState } from 'react';
import SocketContext from '../../contexts/SocketContext';
import { MessageType, RawMessage } from '../common/types';
import { RoleData, RoundData } from './types';

interface UserRoleProps {
  isInGame: boolean;
}

const UserRole: React.FC<UserRoleProps> = ({ isInGame }) => {
  const socket = useContext(SocketContext);
  const [ roles, setRoles ] = useState<RoleData[]>([]);

  const handleRole = useCallback((rawMessage: RawMessage) => {
    if (rawMessage.type === MessageType.GAME_START) {
      const { roles } = rawMessage.message as RoundData;
      setRoles(roles);
    }
  }, []);

  useEffect(() => {
    socket.on('msg', handleRole);
    return () => {
      socket.off('msg', handleRole);
    }
  }, []);

  return (
    <div className={`w-40 h-140 rounded shadow flex flex-col items-center ${isInGame ? '' : 'hidden'}`}>
      <div className='mt-3' />
      {roles.map(x => (
        <div key={x.username} className={`my-5 ease-linear transition-all duration-100 
                                        ${x.role === 'drawer' ? 'text-blue-500'
                                        : x.role === 'winner' ? 'text-green-500'
                                        : 'text-black'}`}>
          {x.nickname} {x.role === 'drawer' ? '🖌️' : x.role === 'spectator' ? '👻' : ''}
        </div>
      ))}
    </div>
  );
}

export default UserRole;