Add bilingual support (German/English) with language selector

- Added language selector in top-left corner
- Implemented data attributes for all translatable text
- Created language management system with localStorage persistence
- Updated all JavaScript functions to support both languages
- Added translations for notifications, error messages, and UI elements
- Maintained existing functionality while adding language switching
This commit is contained in:
2025-09-10 18:42:56 +02:00
parent c84d38b48f
commit 936db67ba4
6 changed files with 239 additions and 66 deletions

View File

@@ -65,15 +65,15 @@ function saveLocationSelection(locationId, locationName) {
// WebSocket Event Handlers
socket.on('connect', () => {
console.log('🔌 WebSocket verbunden');
console.log('🔌 WebSocket connected');
});
socket.on('disconnect', () => {
console.log('🔌 WebSocket getrennt');
console.log('🔌 WebSocket disconnected');
});
socket.on('newTime', (data) => {
console.log('🏁 Neue Zeit empfangen:', data);
console.log('🏁 New time received:', data);
showNotification(data);
// Reload data to show the new time
loadData();
@@ -86,12 +86,13 @@ function showNotification(timeData) {
const notificationSubtitle = document.getElementById('notificationSubtitle');
// Format the time data
const playerName = timeData.player_name || 'Unbekannter Spieler';
const locationName = timeData.location_name || 'Unbekannter Standort';
const playerName = timeData.player_name || (currentLanguage === 'de' ? 'Unbekannter Spieler' : 'Unknown Player');
const locationName = timeData.location_name || (currentLanguage === 'de' ? 'Unbekannter Standort' : 'Unknown Location');
const timeString = timeData.recorded_time || '--:--';
// Update notification content
notificationTitle.textContent = `🏁 Neue Zeit von ${playerName}!`;
const newTimeText = currentLanguage === 'de' ? 'Neue Zeit von' : 'New time from';
notificationTitle.textContent = `🏁 ${newTimeText} ${playerName}!`;
notificationSubtitle.textContent = `${timeString}${locationName}`;
// Show notification
@@ -171,7 +172,8 @@ async function loadLocations() {
locationsData = locations;
// Clear existing options and set default placeholder
locationSelect.innerHTML = '<option value="">📍 Bitte Standort auswählen</option>';
const placeholderText = currentLanguage === 'de' ? '📍 Bitte Standort auswählen' : '📍 Please select location';
locationSelect.innerHTML = `<option value="">${placeholderText}</option>`;
// Add locations from database
locations.forEach(location => {
@@ -230,14 +232,17 @@ async function findNearestLocation() {
// Check if geolocation is supported
if (!navigator.geolocation) {
showLocationError('Geolocation wird von diesem Browser nicht unterstützt.');
const errorMsg = currentLanguage === 'de' ?
'Geolocation wird von diesem Browser nicht unterstützt.' :
'Geolocation is not supported by this browser.';
showLocationError(errorMsg);
return;
}
// Update button state to loading
btn.disabled = true;
btn.classList.add('loading');
btn.textContent = '🔍 Suche...';
btn.textContent = currentLanguage === 'de' ? '🔍 Suche...' : '🔍 Searching...';
try {
// Get user's current position
@@ -283,18 +288,24 @@ async function findNearestLocation() {
} catch (error) {
console.error('Error getting location:', error);
let errorMessage = 'Standort konnte nicht ermittelt werden.';
let errorMessage = currentLanguage === 'de' ? 'Standort konnte nicht ermittelt werden.' : 'Location could not be determined.';
if (error.code) {
switch(error.code) {
case error.PERMISSION_DENIED:
errorMessage = 'Standortzugriff wurde verweigert. Bitte erlaube den Standortzugriff in den Browser-Einstellungen.';
errorMessage = currentLanguage === 'de' ?
'Standortzugriff wurde verweigert. Bitte erlaube den Standortzugriff in den Browser-Einstellungen.' :
'Location access was denied. Please allow location access in browser settings.';
break;
case error.POSITION_UNAVAILABLE:
errorMessage = 'Standortinformationen sind nicht verfügbar.';
errorMessage = currentLanguage === 'de' ?
'Standortinformationen sind nicht verfügbar.' :
'Location information is not available.';
break;
case error.TIMEOUT:
errorMessage = 'Zeitüberschreitung beim Abrufen des Standorts.';
errorMessage = currentLanguage === 'de' ?
'Zeitüberschreitung beim Abrufen des Standorts.' :
'Timeout while retrieving location.';
break;
}
}
@@ -304,7 +315,7 @@ async function findNearestLocation() {
// Reset button state
btn.disabled = false;
btn.classList.remove('loading');
btn.textContent = '📍 Mein Standort';
btn.textContent = currentLanguage === 'de' ? '📍 Mein Standort' : '📍 My Location';
}
}
@@ -315,8 +326,10 @@ function showLocationSuccess(locationName, distance) {
const notificationSubtitle = document.getElementById('notificationSubtitle');
// Update notification content
notificationTitle.textContent = `📍 Standort gefunden!`;
notificationSubtitle.textContent = `${locationName} (${distance.toFixed(1)} km entfernt)`;
const locationFoundText = currentLanguage === 'de' ? 'Standort gefunden!' : 'Location found!';
const distanceText = currentLanguage === 'de' ? 'km entfernt' : 'km away';
notificationTitle.textContent = `📍 ${locationFoundText}`;
notificationSubtitle.textContent = `${locationName} (${distance.toFixed(1)} ${distanceText})`;
// Show notification
notificationBubble.classList.remove('hide');
@@ -338,7 +351,8 @@ function showLocationError(message) {
notificationBubble.style.background = 'linear-gradient(135deg, #dc3545, #c82333)';
// Update notification content
notificationTitle.textContent = '❌ Fehler';
const errorText = currentLanguage === 'de' ? 'Fehler' : 'Error';
notificationTitle.textContent = `${errorText}`;
notificationSubtitle.textContent = message;
// Show notification
@@ -356,15 +370,16 @@ function showLocationError(message) {
// Show prompt when no location is selected
function showLocationSelectionPrompt() {
const rankingList = document.getElementById('rankingList');
const emptyTitle = currentLanguage === 'de' ? 'Standort auswählen' : 'Select Location';
const emptyDescription = currentLanguage === 'de' ?
'Bitte wähle einen Standort aus dem Dropdown-Menü aus<br>oder nutze den "📍 Mein Standort" Button, um automatisch<br>den nächstgelegenen Standort zu finden.' :
'Please select a location from the dropdown menu<br>or use the "📍 My Location" button to automatically<br>find the nearest location.';
rankingList.innerHTML = `
<div class="empty-state">
<div class="empty-icon">📍</div>
<div class="empty-title">Standort auswählen</div>
<div class="empty-description">
Bitte wähle einen Standort aus dem Dropdown-Menü aus<br>
oder nutze den "📍 Mein Standort" Button, um automatisch<br>
den nächstgelegenen Standort zu finden.
</div>
<div class="empty-title">${emptyTitle}</div>
<div class="empty-description">${emptyDescription}</div>
</div>
`;
@@ -410,10 +425,11 @@ async function loadData() {
const leaderboardData = times.map(time => {
const { minutes, seconds, milliseconds } = time.recorded_time;
const timeString = `${minutes}:${seconds.toString().padStart(2, '0')}.${milliseconds}`;
const playerName = time.player ?
`${time.player.firstname} ${time.player.lastname}` :
'Unknown Player';
const locationName = time.location ? time.location.name : 'Unknown Location';
const playerName = time.player ?
`${time.player.firstname} ${time.player.lastname}` :
(currentLanguage === 'de' ? 'Unbekannter Spieler' : 'Unknown Player');
const locationName = time.location ? time.location.name :
(currentLanguage === 'de' ? 'Unbekannter Standort' : 'Unknown Location');
const date = new Date(time.created_at).toISOString().split('T')[0];
return {
@@ -482,34 +498,43 @@ function updateCurrentSelection() {
// Get the display text from the selected option
const locationSelect = document.getElementById('locationSelect');
const selectedLocationOption = locationSelect.options[locationSelect.selectedIndex];
const locationDisplay = selectedLocationOption ? selectedLocationOption.textContent : '📍 Bitte Standort auswählen';
const locationDisplay = selectedLocationOption ? selectedLocationOption.textContent :
(currentLanguage === 'de' ? '📍 Bitte Standort auswählen' : '📍 Please select location');
const periodIcons = {
const periodIcons = currentLanguage === 'de' ? {
'today': '📅 Heute',
'week': '📊 Diese Woche',
'month': '📈 Dieser Monat',
'all': '♾️ Alle Zeiten'
} : {
'today': '📅 Today',
'week': '📊 This Week',
'month': '📈 This Month',
'all': '♾️ All Times'
};
document.getElementById('currentSelection').textContent =
`${locationDisplay}${periodIcons[period]}`;
const lastSyncText = currentLanguage === 'de' ? 'Letzter Sync' : 'Last Sync';
document.getElementById('lastUpdated').textContent =
`Letzter Sync: ${new Date().toLocaleTimeString('de-DE')}`;
`${lastSyncText}: ${new Date().toLocaleTimeString(currentLanguage === 'de' ? 'de-DE' : 'en-US')}`;
}
function updateLeaderboard(data) {
const rankingList = document.getElementById('rankingList');
if (data.length === 0) {
const emptyTitle = currentLanguage === 'de' ? 'Keine Rekorde gefunden' : 'No records found';
const emptyDescription = currentLanguage === 'de' ?
'Für diese Filtereinstellungen liegen noch keine Zeiten vor.<br>Versuche es mit einem anderen Zeitraum oder Standort.' :
'No times available for these filter settings.<br>Try a different time period or location.';
rankingList.innerHTML = `
<div class="empty-state">
<div class="empty-icon">🏁</div>
<div class="empty-title">Keine Rekorde gefunden</div>
<div class="empty-description">
Für diese Filtereinstellungen liegen noch keine Zeiten vor.<br>
Versuche es mit einem anderen Zeitraum oder Standort.
</div>
<div class="empty-title">${emptyTitle}</div>
<div class="empty-description">${emptyDescription}</div>
</div>
`;
return;
@@ -533,7 +558,7 @@ function updateLeaderboard(data) {
trophy = '⭐';
}
const formatDate = new Date(player.date).toLocaleDateString('de-DE', {
const formatDate = new Date(player.date).toLocaleDateString(currentLanguage === 'de' ? 'de-DE' : 'en-US', {
day: '2-digit',
month: 'short'
});
@@ -600,8 +625,99 @@ function startAutoRefresh() {
setInterval(loadData, 45000);
}
// Language Management
let currentLanguage = 'en'; // Default to English
// Translation function
function translateElement(element, language) {
if (element.dataset[language]) {
element.textContent = element.dataset[language];
}
}
// Change language function
function changeLanguage() {
const languageSelect = document.getElementById('languageSelect');
currentLanguage = languageSelect.value;
// Save language preference
localStorage.setItem('ninjacross_language', currentLanguage);
// Translate all elements with data attributes
const elementsToTranslate = document.querySelectorAll('[data-de][data-en]');
elementsToTranslate.forEach(element => {
translateElement(element, currentLanguage);
});
// Update dynamic content
updateDynamicContent();
console.log(`🌐 Language changed to: ${currentLanguage}`);
}
// Update dynamic content that's not in HTML
function updateDynamicContent() {
// Update location select placeholder
const locationSelect = document.getElementById('locationSelect');
if (locationSelect && locationSelect.options[0]) {
locationSelect.options[0].textContent = currentLanguage === 'de' ?
'📍 Bitte Standort auswählen' : '📍 Please select location';
}
// Update find location button
const findLocationBtn = document.getElementById('findLocationBtn');
if (findLocationBtn) {
findLocationBtn.textContent = currentLanguage === 'de' ?
'📍 Mein Standort' : '📍 My Location';
findLocationBtn.title = currentLanguage === 'de' ?
'Nächstgelegenen Standort finden' : 'Find nearest location';
}
// Update refresh button
const refreshBtn = document.querySelector('.refresh-btn');
if (refreshBtn) {
refreshBtn.textContent = currentLanguage === 'de' ?
'⚡ Live Update' : '⚡ Live Update';
}
// Update notification elements
const notificationTitle = document.getElementById('notificationTitle');
const notificationSubtitle = document.getElementById('notificationSubtitle');
if (notificationTitle) {
notificationTitle.textContent = currentLanguage === 'de' ? 'Neue Zeit!' : 'New Time!';
}
if (notificationSubtitle) {
notificationSubtitle.textContent = currentLanguage === 'de' ?
'Ein neuer Rekord wurde erstellt' : 'A new record has been created';
}
// Update current selection display
updateCurrentSelection();
// Reload data to update any dynamic content
if (document.getElementById('locationSelect').value) {
loadData();
} else {
showLocationSelectionPrompt();
}
}
// Load saved language preference
function loadLanguagePreference() {
const savedLanguage = localStorage.getItem('ninjacross_language');
if (savedLanguage && (savedLanguage === 'de' || savedLanguage === 'en')) {
currentLanguage = savedLanguage;
const languageSelect = document.getElementById('languageSelect');
if (languageSelect) {
languageSelect.value = currentLanguage;
}
}
}
// Start the application when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
loadLanguagePreference();
changeLanguage(); // Apply saved language
init();
startAutoRefresh();