class LanguagePicker {
constructor() {
this.config = null;
this.currentLang = null;
}
async init() {
try {
const response = await fetch('/config.json?v=1');
this.config = await response.json();
this.currentLang = this.getCurrentLanguage();
this.createLanguagePicker();
this.addEventListeners();
} catch (error) {
console.error('Error initializing language picker:', error);
}
}
getCurrentLanguage() {
const pathParts = window.location.pathname.split('/').filter(Boolean);
if (pathParts[0] === 'lang' && pathParts[1]) {
return pathParts[1];
}
return this.config.site.defaultLang;
}
createLanguagePicker() {
const template = `
${this.createLanguageOptions()}
`;
let container = document.getElementById('language-picker-container');
if (!container) {
container = document.createElement('div');
container.id = 'language-picker-container';
container.className = 'fixed top-0 left-0 right-0 bg-white shadow-md z-50 flex justify-end px-4 py-2';
document.body.appendChild(container);
}
container.innerHTML = template;
}
createLanguageOptions() {
const currentPath = window.location.pathname;
const currentLang = this.getCurrentLanguage();
return Object.entries(this.config.languages)
.map(([code, lang]) => {
let relativePath = '';
if (currentLang === this.config.site.defaultLang) {
relativePath = currentPath;
} else {
const pathParts = currentPath.split('/');
relativePath = '/' + pathParts.slice(3).join('/');
}
const targetPath = code === this.config.site.defaultLang
? relativePath || '/'
: `/lang/${code}${relativePath}`;
return `