// Login page i18n and theme switching
// Translations for login page strings (curated set of common languages)
const LOGIN_TRANSLATIONS = {
en: {
title: "Log into your instance",
instance_url: "Instance URL",
authorize: "Authorize",
note_label: "Note:",
note_text: "this application is completely client-side, meaning everything happens in the browser on your machine. It does not store information anywhere else than your browser's local storage.",
source_code: "Source code",
please_wait: "Please wait",
registering: "Registering app",
authorizing: "Authorizing",
getting_token: "Getting token",
invalid_instance: "Invalid instance",
theme_dark: "Dark",
theme_light: "Light",
theme_contrast: "High contrast",
},
"zh-CN": {
title: "登录你的实例",
instance_url: "实例地址",
authorize: "授权",
note_label: "注意:",
note_text: "本应用完全在客户端运行,所有操作都在你的浏览器中完成。除了浏览器的本地存储外,不会在其他地方存储信息。",
source_code: "源代码",
please_wait: "请稍候",
registering: "正在注册应用",
authorizing: "正在授权",
getting_token: "正在获取令牌",
invalid_instance: "无效的实例",
theme_dark: "暗色",
theme_light: "亮色",
theme_contrast: "高对比度",
},
"zh-TW": {
title: "登入你的實例",
instance_url: "實例網址",
authorize: "授權",
note_label: "注意:",
note_text: "本應用完全在客戶端運行,所有操作都在你的瀏覽器中完成。除了瀏覽器的本地儲存外,不會在其他地方儲存資訊。",
source_code: "原始碼",
please_wait: "請稍候",
registering: "正在註冊應用",
authorizing: "正在授權",
getting_token: "正在取得權杖",
invalid_instance: "無效的實例",
theme_dark: "暗色",
theme_light: "亮色",
theme_contrast: "高對比度",
},
ja: {
title: "インスタンスにログイン",
instance_url: "インスタンスURL",
authorize: "認証",
note_label: "注意:",
note_text: "このアプリケーションは完全にクライアントサイドで動作します。すべての処理はブラウザ上で行われ、ブラウザのローカルストレージ以外にデータを保存しません。",
source_code: "ソースコード",
please_wait: "お待ちください",
registering: "アプリを登録中",
authorizing: "認証中",
getting_token: "トークンを取得中",
invalid_instance: "無効なインスタンス",
theme_dark: "ダーク",
theme_light: "ライト",
theme_contrast: "ハイコントラスト",
},
ko: {
title: "인스턴스에 로그인",
instance_url: "인스턴스 URL",
authorize: "인증",
note_label: "참고:",
note_text: "이 애플리케이션은 완전히 클라이언트 측에서 동작합니다. 모든 작업은 브라우저에서 이루어지며, 브라우저의 로컬 저장소 외에는 어디에도 정보를 저장하지 않습니다.",
source_code: "소스 코드",
please_wait: "잠시 기다려주세요",
registering: "앱 등록 중",
authorizing: "인증 중",
getting_token: "토큰 받는 중",
invalid_instance: "잘못된 인스턴스",
theme_dark: "다크",
theme_light: "라이트",
theme_contrast: "고대비",
},
de: {
title: "Bei deiner Instanz anmelden",
instance_url: "Instanz-URL",
authorize: "Autorisieren",
note_label: "Hinweis:",
note_text: "Diese Anwendung läuft vollständig clientseitig. Alles geschieht in deinem Browser. Daten werden nur im lokalen Speicher deines Browsers gespeichert.",
source_code: "Quellcode",
please_wait: "Bitte warten",
registering: "App wird registriert",
authorizing: "Autorisierung",
getting_token: "Token wird abgerufen",
invalid_instance: "Ungültige Instanz",
theme_dark: "Dunkel",
theme_light: "Hell",
theme_contrast: "Hoher Kontrast",
},
fr: {
title: "Connectez-vous à votre instance",
instance_url: "URL de l'instance",
authorize: "Autoriser",
note_label: "Note :",
note_text: "cette application fonctionne entièrement côté client. Tout se passe dans votre navigateur. Aucune donnée n'est stockée ailleurs que dans le stockage local de votre navigateur.",
source_code: "Code source",
please_wait: "Veuillez patienter",
registering: "Enregistrement de l'application",
authorizing: "Autorisation",
getting_token: "Obtention du jeton",
invalid_instance: "Instance invalide",
theme_dark: "Sombre",
theme_light: "Clair",
theme_contrast: "Contraste élevé",
},
es: {
title: "Inicia sesión en tu instancia",
instance_url: "URL de la instancia",
authorize: "Autorizar",
note_label: "Nota:",
note_text: "esta aplicación funciona completamente en el lado del cliente. Todo ocurre en tu navegador. No almacena información en ningún otro lugar que no sea el almacenamiento local de tu navegador.",
source_code: "Código fuente",
please_wait: "Por favor espera",
registering: "Registrando aplicación",
authorizing: "Autorizando",
getting_token: "Obteniendo token",
invalid_instance: "Instancia inválida",
theme_dark: "Oscuro",
theme_light: "Claro",
theme_contrast: "Alto contraste",
},
pt: {
title: "Entrar na sua instância",
instance_url: "URL da instância",
authorize: "Autorizar",
note_label: "Nota:",
note_text: "esta aplicação funciona inteiramente no lado do cliente. Tudo acontece no seu navegador. Não armazena informações em nenhum outro lugar além do armazenamento local do seu navegador.",
source_code: "Código-fonte",
please_wait: "Aguarde",
registering: "Registrando aplicação",
authorizing: "Autorizando",
getting_token: "Obtendo token",
invalid_instance: "Instância inválida",
theme_dark: "Escuro",
theme_light: "Claro",
theme_contrast: "Alto contraste",
},
ru: {
title: "Войти в свой инстанс",
instance_url: "URL инстанса",
authorize: "Авторизовать",
note_label: "Примечание:",
note_text: "это приложение полностью работает на стороне клиента. Все происходит в вашем браузере. Данные хранятся только в локальном хранилище вашего браузера.",
source_code: "Исходный код",
please_wait: "Пожалуйста, подождите",
registering: "Регистрация приложения",
authorizing: "Авторизация",
getting_token: "Получение токена",
invalid_instance: "Недействительный инстанс",
theme_dark: "Тёмная",
theme_light: "Светлая",
theme_contrast: "Высокая контрастность",
},
};
// Language display names (native names)
const LANGUAGE_NAMES = {
en: "English",
"zh-CN": "简体中文",
"zh-TW": "繁體中文",
ja: "日本語",
ko: "한국어",
de: "Deutsch",
fr: "Français",
es: "Español",
pt: "Português",
ru: "Русский",
};
const STORAGE_KEY_LOCALE = "masto-fe-locale";
const STORAGE_KEY_SETTINGS = "mastodon-settings";
function getStoredLocale() {
return localStorage.getItem(STORAGE_KEY_LOCALE);
}
function getStoredTheme() {
try {
const settings = JSON.parse(localStorage.getItem(STORAGE_KEY_SETTINGS));
return settings?.theme;
} catch {
return null;
}
}
function setStoredLocale(locale) {
localStorage.setItem(STORAGE_KEY_LOCALE, locale);
}
function setStoredTheme(theme) {
let settings;
try {
settings = JSON.parse(localStorage.getItem(STORAGE_KEY_SETTINGS)) || {};
} catch {
settings = {};
}
settings.theme = theme;
localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(settings));
}
function detectLocale() {
const stored = getStoredLocale();
if (stored && LOGIN_TRANSLATIONS[stored]) return stored;
const browserLang = navigator.language;
// Try exact match first
if (LOGIN_TRANSLATIONS[browserLang]) return browserLang;
// Try language without region (e.g., "zh" -> "zh-CN")
const base = browserLang.split("-")[0];
// Special case for Chinese
if (base === "zh") {
if (browserLang.includes("TW") || browserLang.includes("HK")) return "zh-TW";
return "zh-CN";
}
if (LOGIN_TRANSLATIONS[base]) return base;
return "en";
}
function resolveLocale(locale) {
// Map locale codes used by the main app to login page translations
// The main app uses locale codes like "zh-CN", but navigator.language
// might return "zh-Hans-CN" etc.
if (LOGIN_TRANSLATIONS[locale]) return locale;
const base = locale.split("-")[0];
if (base === "zh") return "zh-CN";
if (LOGIN_TRANSLATIONS[base]) return base;
return "en";
}
function applyTranslations(locale) {
const resolved = resolveLocale(locale);
const strings = LOGIN_TRANSLATIONS[resolved] || LOGIN_TRANSLATIONS.en;
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.getAttribute("data-i18n");
if (strings[key]) {
el.textContent = strings[key];
}
});
// Update theme select option labels
const themeSelect = document.getElementById("theme-select");
if (themeSelect) {
themeSelect.options[0].text = strings.theme_dark;
themeSelect.options[1].text = strings.theme_light;
themeSelect.options[2].text = strings.theme_contrast;
}
document.documentElement.lang = locale;
}
function applyTheme(theme) {
document.documentElement.setAttribute("data-theme", theme);
}
// Make translation function available to auth.js
window.loginI18n = function (key) {
const locale = resolveLocale(
getStoredLocale() || detectLocale()
);
const strings = LOGIN_TRANSLATIONS[locale] || LOGIN_TRANSLATIONS.en;
return strings[key] || key;
};
document.addEventListener("DOMContentLoaded", function () {
// Initialize theme
const theme = getStoredTheme() || "mastodon";
applyTheme(theme);
const themeSelect = document.getElementById("theme-select");
if (themeSelect) {
themeSelect.value = theme;
themeSelect.addEventListener("change", function () {
applyTheme(this.value);
setStoredTheme(this.value);
});
}
// Initialize language selector
const langSelect = document.getElementById("lang-select");
if (langSelect) {
Object.entries(LANGUAGE_NAMES).forEach(([code, name]) => {
const option = document.createElement("option");
option.value = code;
option.textContent = name;
langSelect.appendChild(option);
});
const locale = detectLocale();
langSelect.value = locale;
applyTranslations(locale);
langSelect.addEventListener("change", function () {
const newLocale = this.value;
setStoredLocale(newLocale);
applyTranslations(newLocale);
});
}
});