~cytrogen/masto-fe

ref: 5809fa395e81f60a7f447b9a512103f21e0e69d7 masto-fe/public/login-i18n.js -rw-r--r-- 10.8 KiB
5809fa39 — Cytrogen [feature] Login page improvements and i18n 4 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// 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);
    });
  }
});