import React, { useState, KeyboardEvent, useRef } from "react"; import { Input, Button, Box, Typography, Tooltip, Dialog, DialogTitle, DialogContent, DialogActions } from "@mui/material"; import { Session } from "./GlobalContext"; interface NameSetterProps { session: Session; sendJsonMessage: (message: any) => void; onNameSet?: () => void; initialName?: string; initialPassword?: string; } const NameSetter: React.FC = ({ session, sendJsonMessage, onNameSet, initialName = "", initialPassword = "", }) => { const [editName, setEditName] = useState(initialName); const [editPassword, setEditPassword] = useState(initialPassword); const [showDialog, setShowDialog] = useState(!session.name); const [isSubmitting, setIsSubmitting] = useState(false); const nameInputRef = useRef(null); const passwordInputRef = useRef(null); const setName = (name: string) => { setIsSubmitting(true); sendJsonMessage({ type: "set_name", data: { name, password: editPassword ? editPassword : undefined }, }); if (onNameSet) { onNameSet(); } setShowDialog(false); setIsSubmitting(false); setEditName(""); setEditPassword(""); }; const handleNameKeyDown = (event: KeyboardEvent): void => { if (event.key === "Enter") { event.preventDefault(); if (passwordInputRef.current) { passwordInputRef.current.focus(); } } }; const handlePasswordKeyDown = (event: KeyboardEvent): void => { if (event.key === "Enter") { event.preventDefault(); handleSubmit(); } }; const handleSubmit = () => { const newName = editName.trim(); if (!newName || (session?.name && session.name === newName)) { return; } setName(newName); }; const handleOpenDialog = () => { setEditName(session.name || ""); setEditPassword(""); setShowDialog(true); // Focus the name input when dialog opens setTimeout(() => { if (nameInputRef.current) { nameInputRef.current.focus(); } }, 100); }; const handleCloseDialog = () => { setShowDialog(false); setEditName(""); setEditPassword(""); }; const hasNameChanged = editName.trim() !== (session.name || ""); const canSubmit = editName.trim() && hasNameChanged && !isSubmitting; return ( {session.name && !showDialog && ( You are logged in as: {session.name} )} {/* Dialog for name change */} {session.name ? "Change Your Name" : "Enter Your Name"} {session.name ? "Enter a new name to change your current name." : "Enter your name to join the lobby." } You can optionally set a password to reserve this name; supply it again to takeover the name from another client. { setEditName(e.target.value); }} onKeyDown={handleNameKeyDown} placeholder="Your name" fullWidth autoFocus /> setEditPassword(e.target.value)} onKeyDown={handlePasswordKeyDown} placeholder="Optional password" fullWidth /> ); }; export default NameSetter;