.bottomRectangle.inactive {
background-color: #666666; /* Light gray color /
color: #fff; / Ensure text is still visible /
cursor: not-allowed; / Indicate the button is not clickable */
}
// Функция обработки повторного подключения
const handleReconnection = () => {
// Повторно отправляем несообщенные действия
resendUnsentActions();
// Получаем последние данные с сервера
fetchLatestDataFromServer();
};
// Функция повторной отправки несообщенных действий
const resendUnsentActions = () => {
while (unsentActionsQueueRef.current.length > 0) {
const action = unsentActionsQueueRef.current.shift();
action();
}
};
// Функция получения последних данных с сервера
const fetchLatestDataFromServer = async () => {
try {
const response = await fetch(${server_url}/api/user/${code});
if (response.ok) {
const data = await response.json();
setUserData(data);
updateActiveCircle(data);
} else {
console.error('Failed to fetch latest data');
}
} catch (error) {
console.error('Error fetching latest data:', error);
}
};
// Функция отправки данных на сервер с обработкой ошибок и очередью
const sendDataToServer = async (action, data) => {
if (navigator.onLine) {
try {
let response;
if (action === 'updateScore') {
response = await fetch(`{server_url}/api/update-score`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
} else if (action === 'updateApproveState') {
response = await fetch({server_url}/api/update-approve-state, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
}
if (response.ok) {
console.log(${action} successfully sent to server);
} else {
console.error(Failed to send ${action} to server);
unsentActionsQueueRef.current.push(() => sendDataToServer(action, data));
}
} catch (error) {
console.error('Error sending ${action} to server:', error);
unsentActionsQueueRef.current.push(() => sendDataToServer(action, data));
}
} else {
// Если оффлайн, добавляем действие в очередь
unsentActionsQueueRef.current.push(() => sendDataToServer(action, data));
}
};
// Модифицированная функция обновления состояния подтверждения
const updateApproveState = async () => {
if (!activeCircle || activeCircle.status !== "active" || !userData || activeCircle.playerGame.fishCount === null || activeCircle.opponentGame.fishCount === null) return;
// Обновляем локальные данные
const activeCircleIndex = userData.circles.findIndex(circle => circle.number === activeCircle.number && circle.status === 'active');
if (activeCircleIndex !== -1) {
let updatedUserData = { ...userData };
let updatedActiveCircle = { ...updatedUserData.circles[activeCircleIndex] };
// Обновляем approveState
if (updatedActiveCircle.playerGame.approveState === 1) {
updatedActiveCircle.playerGame.approveState = 2;
} else if (updatedActiveCircle.playerGame.approveState === 2) {
updatedActiveCircle.playerGame.approveState = 1;
} else if (updatedActiveCircle.playerGame.approveState === 3) {
updatedActiveCircle.playerGame.approveState = 4;
} else if (updatedActiveCircle.playerGame.approveState === 4) {
updatedActiveCircle.playerGame.approveState = 3;
}
updatedUserData.circles[activeCircleIndex] = updatedActiveCircle;
setUserData(updatedUserData);
setActiveCircle(updatedActiveCircle);
// Подготавливаем данные для отправки
const dataToSend = { userData: updatedUserData, activeCircleNumber: activeCircle.number };
// Отправляем данные на сервер
sendDataToServer('updateApproveState', dataToSend);
}
};
// Модифицированная функция обработки изменения ввода очков
const handleScoreInputChange = (e) => {
let value = e.target.value;
if (value === '' || isNaN(value) || parseInt(value) > 99) {
value = 0;
} else {
value = parseInt(value);
}
setPlayerScoreInput(value);
};
export default Tournament;
Это сам клиент, я бы хотел добавить внутрь в bluerectangleleft вниз кнопку enter и перенести отправку данных из handleScoreInputBlur в эту кнопку с проверкой на то, что значение отправляемое поменялось
В общем желательно улучшить мои стили для адптивности и работы на ios, добавить кнопку enter
Certainly! Let's work through the steps to modify your code as per your requirements:
Add an 'Enter' Button Inside blueRectangleLeft
We'll add an 'Enter' button at the bottom of the blueRectangleLeft div and remove the data sending from handleScoreInputBlur. Instead, we'll move this logic to a new function, handleEnterButtonClick, which will be triggered when the 'Enter' button is clicked.
Move Data Sending Logic to the Button Click Handler
We'll create a new function handleEnterButtonClick that will handle sending the data to the server when the 'Enter' button is clicked. This function will include a check to ensure that the value being sent has actually changed.
Improve Styles for Responsive Design and iOS Compatibility
We'll adjust your CSS to make the layout more responsive and ensure better compatibility with iOS devices. This includes using relative units, ensuring touch targets are appropriately sized, and adjusting layouts for different screen sizes.
1. Modify the JSX to Include the 'Enter' Button
In your Tournament component, update the JSX inside the blueRectangleLeft div to include the 'Enter' button:
We added a fragment <>...</> to wrap the input and the button together.
Removed the onBlur event from the input since we don't want to send data on blur anymore.
Added a button with the class enterButton and an onClick handler handleEnterButtonClick.
2. Create handleEnterButtonClick Function
Add the following code to your component:
const [previousScoreInput, setPreviousScoreInput] = useState(null);
useEffect(() => {
if (activeCircle) {
setPlayerScoreInput(activeCircle.playerGame.fishCount);
setPreviousScoreInput(activeCircle.playerGame.fishCount);
}
}, [activeCircle]);
const handleEnterButtonClick = () => {
let newPlayerScoreInput;
if (playerScoreInput === '' || isNaN(playerScoreInput)) {
newPlayerScoreInput = 0;
} else {
newPlayerScoreInput = parseInt(playerScoreInput, 10);
}
if (newPlayerScoreInput !== previousScoreInput) {
const activeCircleIndex = userData.circles.findIndex(circle => circle.number === activeCircle.number && circle.status === 'active');
if (activeCircleIndex !== -1) {
let updatedUserData = { ...userData };
updatedUserData.circles[activeCircleIndex].playerGame.fishCount = newPlayerScoreInput;
setPlayerScoreInput(newPlayerScoreInput);
setUserData(updatedUserData);
setActiveCircle(updatedUserData.circles[activeCircleIndex]);
// Prepare data to send
const dataToSend = { userData: updatedUserData, activeCircleNumber: activeCircle.number };
// Send data to server
sendDataToServer('updateScore', dataToSend);
// Update previousScoreInput
setPreviousScoreInput(newPlayerScoreInput);
}
}
};
Explanation:
Introduced a new state variable previousScoreInput to store the previous score value.
Updated useEffect to set previousScoreInput whenever activeCircle changes.
In handleEnterButtonClick, we compare newPlayerScoreInput with previousScoreInput. If they are different, we proceed to update the state and send data to the server.
After sending the data, we update previousScoreInput to the new value.
3. Adjust CSS Styles for the 'Enter' Button and Responsiveness
Add the following styles to your CSS to style the 'Enter' button and adjust layouts:
Set flex-direction: column on .blueRectangleLeft to arrange the input and button vertically.
Added padding and adjusted margins for proper spacing.
Styled the enterButton for visibility and touch-friendliness.
Included a media query to adjust font sizes on smaller screens for better readability.
4. Improve Styles for Responsive Design and iOS Compatibility
Here's a general approach to enhance responsiveness and iOS compatibility:
Use Relative Units: Replace fixed units like px with relative units like vh, vw, %, or em to make the layout adapt to different screen sizes.
Adjust Touch Target Sizes: Ensure that buttons and interactive elements are large enough for touch interactions. Apple recommends a minimum hit area of 44x44 points for iOS devices.
Test on iOS Devices: Use tools like the iOS Simulator or physical devices to test the interface and interactions.
Viewport Meta Tag: Ensure that the HTML document includes the viewport meta tag to control layout on mobile browsers:
Ensure all new CSS classes like .enterButton are properly defined in your CSS file.
Test the application on different devices, especially iOS devices, to ensure that the UI elements are rendered correctly and that touch interactions work as expected.
Adjust the font-size, padding, and other styles in the media queries to suit your design preferences.
Remember to handle edge cases where the user might input invalid data.
By following these steps, you should have an 'Enter' button inside blueRectangleLeft that sends data when clicked, and your application should have improved responsiveness and better compatibility with iOS devices.